/**
 Created by Administrator on 2016/6/14.
 */

// var serviceHttp = 'http://intelab.ilabservice.cloud/';
var serviceHttp = 'http://inmycars.ihengtian.top:8998/';
// var serviceHttp = 'http://192.168.1.72:8998/';

var c_user = "";

/*index-路由*/
var indexapp = angular.module('indexRoute', ['ngRoute', 'ngAnimate']);
//,locationProvider
function routeConfig($routeProvider) {
    $routeProvider.when('/', {
        controller: 'mainController',
        templateUrl: 'lou_distribute.html'
    }).when('/lou/:louId', {
        controller: 'louController',
        templateUrl: 'lou_distribute.html'
    }).when('/ceng_distribute.html/:buildId/:louName', {
        controller: 'cengController',
        templateUrl: 'ceng_distribute.html'
    }).when('/shi_distribute.html/:floorId/:floorName', {
        controller: 'shiController',
        templateUrl: 'shi_distribute.html'
    }).when('/unit_distribute.html/:roomId', {
        controller: 'unitController',
        templateUrl: 'unit_distribute.html'
    }).when('/unit_Details.html/:unitId', {
        controller: 'unitDetailController',
        templateUrl: 'unit_Details.html'
    }).when('/set', {
        controller: 'settingController',
        templateUrl: 'Setting.html'
    }).when('/userList', {
        controller: 'userListController',
        templateUrl: 'userList.html'
    }).when('/userList.html', {
        controller: 'userListController',
        templateUrl: 'userList.html'
    }).when('/userUnit', {
        controller: 'userUnitController',
        templateUrl: 'userUnit.html'
    }).when('/userDetails', {
        controller: 'userDetailsController',
        templateUrl: 'userDetails.html'
    }).when('/chartReport', {
        controller: 'chartReportController',
        templateUrl: 'chartReport.html'
    }).when('/platformUser', {
        controller: 'plateformUserController',
        templateUrl: 'plateformUser.html'
    }).when('/companyList', {
        controller: 'companyListController',
        templateUrl: 'companyList.html'
    }).when('/companyList.html', {
        controller: 'companyListController',
        templateUrl: 'companyList.html'
    }).when('/mapshow', {
        controller: 'mapshowController',
        templateUrl: 'mapshow.html'
    }).when('/companySet', {
        controller: 'settingController',
        templateUrl: 'companySet.html'
    }).when('/personalData', {
        controller: 'personalDataController',
        templateUrl: 'personalData.html'
    }).when('/unitlist', {
        controller: 'unitlistController',
        templateUrl: 'unitlist.html'
    }).when('/version', {
        controller: 'versionController',
        templateUrl: 'version.html'
    }).otherwise({
        redirectTo: '/'
    });
    //AngularJS 中的友好 URL —— 移除URL 中的 #
    /*
     1,配置 $locationProvider ---- $locationProvider.html5Mode(true);
     2,设置我们的相对连接的起点路径 ----- 为相对链接设置<base href="/">(href 设置起点路径)
     */
    // $locationProvider.html5Mode(true);
};

indexapp.config(routeConfig);

indexapp.run(['$rootScope', '$location', function ($rootScope, $location) {
    $rootScope.$on("$locationChangeSuccess", function (event, next, current) {
        var temp = next.indexOf('#');
        next = temp > 0 ? next.substr(temp + 1) : '/companyList';
        var nextChart = next.split('/')[1];
        temp = current.indexOf('#');
        current = temp > 0 ? current.substr(temp + 1) : '/';
        var currentChart = current.split('/')[1];
        if (next == '/' || current == "/" || current == "/lou" || current == "/set" || current == "/userList" || current == "/userUnit" || current == "/userDetails" || current == "/chartReport" || current == "/platformUser" || current == "/companyList" || current == "/companyList.html" || current == "/mapshow" || current == "/companySet" || current == "/personalData" || current == "/unitlist" || current == "/version" || currentChart == "unit_Details.html") {

            if(currentChart != "ceng_distribute.html"){
                if (nextChart == "ceng_distribute.html" || nextChart == "shi_distribute.html" || nextChart == "unit_distribute.html" || nextChart == "unit_Details.html") {
                    $("#history_go").show();
                } else {
                    $("#history_go").hide();
                }
            }else {
                $("#history_go").hide();
            }

        } else {
            $("#history_go").show();
        }
    });
}]);
/*首页分布*/

jQuery.extend({
    createUploadIframe: function (id, uri) {
        //create frame
        var frameId = 'jUploadFrame' + id;
        var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"';
        if (window.ActiveXObject) {
            if (typeof uri == 'boolean') {
                iframeHtml += ' src="' + 'javascript:false' + '"';

            }
            else if (typeof uri == 'string') {
                iframeHtml += ' src="' + uri + '"';

            }
        }
        iframeHtml += ' />';
        jQuery(iframeHtml).appendTo(document.body);

        return jQuery('#' + frameId).get(0);
    },

    createUploadForm: function (id, fileElementId, data, fileElement) {
        //create form
        var formId = 'jUploadForm' + id;
        var fileId = 'jUploadFile' + id;
        var form = jQuery('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
        if (data) {
            for (var i in data) {
                jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);
            }
        }
        var oldElement;
        if (fileElement == null)
            oldElement = jQuery('#' + fileElementId);
        else
            oldElement = fileElement;

        var newElement = jQuery(oldElement).clone();
        jQuery(oldElement).attr('id', fileId);
        jQuery(oldElement).before(newElement);
        jQuery(oldElement).appendTo(form);

        //set attributes
        jQuery(form).css('position', 'absolute');
        jQuery(form).css('top', '-1200px');
        jQuery(form).css('left', '-1200px');
        jQuery(form).appendTo('body');
        return form;
    },

    ajaxFileUpload: function (s) {
        // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
        s = jQuery.extend({}, jQuery.ajaxSettings, s);
        var id = new Date().getTime()
        var form = jQuery.createUploadForm(id, s.fileElementId, (typeof(s.data) == 'undefined' ? false : s.data), s.fileElement);
        var io = jQuery.createUploadIframe(id, s.secureuri);
        var frameId = 'jUploadFrame' + id;
        var formId = 'jUploadForm' + id;
        // Watch for a new set of requests
        if (s.global && !jQuery.active++) {
            jQuery.event.trigger("ajaxStart");
        }
        var requestDone = false;
        // Create the request object
        var xml = {}
        if (s.global)
            jQuery.event.trigger("ajaxSend", [xml, s]);
        // Wait for a response to come back
        var uploadCallback = function (isTimeout) {
            var io = document.getElementById(frameId);
            try {
                if (io.contentWindow) {
                    xml.responseText = io.contentWindow.document.body ? io.contentWindow.document.body.innerHTML : null;
                    xml.responseXML = io.contentWindow.document.XMLDocument ? io.contentWindow.document.XMLDocument : io.contentWindow.document;

                } else if (io.contentDocument) {
                    xml.responseText = io.contentDocument.document.body ? io.contentDocument.document.body.innerHTML : null;
                    xml.responseXML = io.contentDocument.document.XMLDocument ? io.contentDocument.document.XMLDocument : io.contentDocument.document;
                }
            } catch (e) {
                jQuery.handleError(s, xml, null, e);
            }
            if (xml || isTimeout == "timeout") {
                requestDone = true;
                var status;
                try {
                    status = isTimeout != "timeout" ? "success" : "error";
                    // Make sure that the request was successful or notmodified
                    if (status != "error") {
                        // process the data (runs the xml through httpData regardless of callback)
                        var data = jQuery.uploadHttpData(xml, s.dataType);
                        // If a local callback was specified, fire it and pass it the data
                        if (s.success)
                            s.success(data, status);

                        // Fire the global callback
                        if (s.global)
                            jQuery.event.trigger("ajaxSuccess", [xml, s]);
                    } else
                        jQuery.handleError(s, xml, status);
                } catch (e) {
                    status = "error";
                    jQuery.handleError(s, xml, status, e);
                }

                // The request was completed
                if (s.global)
                    jQuery.event.trigger("ajaxComplete", [xml, s]);

                // Handle the global AJAX counter
                if (s.global && !--jQuery.active)
                    jQuery.event.trigger("ajaxStop");

                // Process result
                if (s.complete)
                    s.complete(xml, status);

                jQuery(io).unbind()

                setTimeout(function () {
                    try {
                        jQuery(io).remove();
                        jQuery(form).remove();

                    } catch (e) {
                        jQuery.handleError(s, xml, null, e);
                    }

                }, 100)

                xml = null

            }
        }
        // Timeout checker
        if (s.timeout > 0) {
            setTimeout(function () {
                // Check to see if the request is still happening
                if (!requestDone) uploadCallback("timeout");
            }, s.timeout);
        }
        try {

            var form = jQuery('#' + formId);
            jQuery(form).attr('action', s.url);
            jQuery(form).attr('method', 'POST');
            jQuery(form).attr('target', frameId);
            if (form.encoding) {
                jQuery(form).attr('encoding', 'multipart/form-data');
            }
            else {
                jQuery(form).attr('enctype', 'multipart/form-data');
            }
            jQuery(form).submit();

        } catch (e) {
            jQuery.handleError(s, xml, null, e);
        }

        jQuery('#' + frameId).load(uploadCallback);
        return {
            abort: function () {
                try {
                    jQuery('#' + frameId).remove();
                    jQuery(form).remove();
                }
                catch (e) {
                }
            }
        };
    },

    uploadHttpData: function (r, type) {
        var data = !type;
        data = type == "xml" || data ? r.responseXML : r.responseText;

        // If the type is "script", eval it in global context
        if (type == "script")
            jQuery.globalEval(data);
        // Get the JavaScript object, if JSON is used.
        if (type == "json")
            eval("data = " + data);
        // evaluate scripts within html
        if (type == "html")
            jQuery("<div>").html(data).evalScripts();

        return data;
    },

    handleError: function (s, xml, status, e) {
        // If a local callback was specified, fire it
        if (s.error)
            s.error(xml, status, e);

        // Fire the global callback
        if (s.global)
            jQuery.event.trigger("ajaxError", [xml, s, e]);
    }
});

indexapp.controller('mainController', function ($scope, $http, $location) {

    //返回上一级
    $("#history_go").on('click', function () {
        var href = location.href.split('/')[1];
        if(href==""){
            $("#history_go").hide();
        }
        window.location.href = "javascript:history.go(-1);"
    });
    // document.cookie = "JSESSIONID=AB5643A7A58EA12FC7436F923E9D586A";
    $scope.preview = function (file, imgId) {
        var img = $('#' + imgId),
            url = URL.createObjectURL(file);
        img.unbind();
        img.bind('load', function () {
            URL.revokeObjectURL(url);
        })
        img.attr('src', url);
    }
    $("#logofileToUpload").unbind('change').change(function (e) {
        var file = e.target.files[0];
        $scope.preview(file, 'addlogoPhotoNew');
    });
    //修改企业logo初始化
    $scope.updateLogoInit = function () {
        $("#logofileToUpload").val('');
        $("#addlogoPhotoNew").attr('src', '');
        $http.get(serviceHttp + 'api/rest/firm/person/mine/info').success(function (res) {
            //只有企业管理员才可以修改企业logo
            if (res.data.role.roleAuthority.name == 'FIRM_MANAGER') {
                $scope.hasUpdataLogo = 1; //有权限修改企业logo
            } else {
                $scope.hasUpdataLogo = 0;//无权限修改企业logo
            }
            //平台显示InteLab图片，不能修改
            if (res.data.role.roleAuthority.name == 'SERVICE_BUSINESS' || res.data.role.roleAuthority.name == 'SERVICE_MANAGER') {
                $scope.currentUser.companyLogo = 'image/qylogo.png';
            } else {
                if (res.data && res.data.companyLogo) {
                    $scope.currentUser.companyLogo = serviceHttp + res.data.companyLogo;
                } else {
                    $scope.currentUser.companyLogo = 'image/qylogo.png';
                }
            }
        });
    }

    //保存修改logo
    $scope.SaveUpdateLogoInfo = function () {
        var path = $("#logofileToUpload").val();

        if (path) {
            $.ajaxFileUpload({
                url: serviceHttp + 'api/rest/file/logo/company',
                secureuri: false,
                fileElementId: 'logofileToUpload',//file控件id
                success: function (res) {
                    $http.get(serviceHttp + 'api/rest/firm/person/mine/info').success(function (resq) {
                        $scope.currentUser = resq.data;
                    });
                }
            });
        }

    }
    $http.getData = function (url) {
        return $http.get(url).error(function (data, status) {
            if (data.status == "403") {
                layer.msg("您还未登录，请先登录！");
                window.location.href = 'Lab_login.html';
            } else {
                layer.msg(status);
            }
        });
    }
    $scope.redirect = function (url) {
        $location.url(url);
    }
    $("#logofileToUpload").unbind('change').change(function (e) {
        var file = e.target.files[0];
        $scope.preview(file, 'addlogoPhotoNew');
    });

    // menuList
    $scope.menuList = [];
    $http.get(serviceHttp + 'api/rest/firm/person/mine/info').success(function (res) {

        $scope.setmenuStyle = function (menu) {
            for (var i = 0; i < $scope.menuList.length; i++) {
                $scope.menuList[i].background = $scope.menuList[i].photobg;
                $scope.menuList[i].style = {
                    'color': "#FFFFFF"
                };
            }
            menu.background = menu.photoselect;
            menu.style = {
                'color': "#06AAFC"
            };
        }
        $scope.currentUser = res.data;
        if ($scope.currentUser.role.roleAuthority.name == 'FIRM_MANAGER') {
            $scope.menuList = [
                {
                    name: '主 页',
                    url: '#/lou',
                    menuId: 'lou-Distribute',
                    photobg: 'image/index-bg.png',
                    photoselect: 'image/index-select.png'
                },
                {
                    name: '设 置',
                    url: '#/set',
                    menuId: 'plate-set',
                    photobg: 'image/set-bg.png',
                    photoselect: 'image/set-select.png'
                },
                {
                    name: '用户列表',
                    url: '#/userList',
                    menuId: 'user-List',
                    photobg: 'image/user-bg.png',
                    photoselect: 'image/user-select.png'
                },
                {
                    name: '用户设备',
                    url: '#/userUnit',
                    menuId: 'user-Unit',
                    photobg: 'image/userunit-bg.png',
                    photoselect: 'image/userunit-select.png'
                },
                {
                    name: '统计报告',
                    url: '#/chartReport',
                    menuId: 'chart-Report',
                    photobg: 'image/tjbg-bg.png',
                    photoselect: 'image/tjbg-select.png'
                }
            ];
        } else if ($scope.currentUser.role.roleAuthority.name == 'SERVICE_BUSINESS') {
            $scope.redirect("companyList.html");
            $scope.menuList = [
                {
                    name: '公司列表',
                    url: '#/companyList',
                    menuId: 'company-List',
                    photobg: 'image/index-bg.png',
                    photoselect: 'image/index-select.png'
                },
                {
                    name: '地图展示',
                    url: '#/mapshow',
                    menuId: 'map-Show',
                    photobg: 'image/index-bgmap.png',
                    photoselect: 'image/index-selectmap.png'
                },
                {
                    name: '设备种类',
                    url: '#/companySet',
                    menuId: 'company-Set',
                    photobg: 'image/set.png',
                    photoselect: 'image/set-select.png'
                }
            ];
        } else if ($scope.currentUser.role.roleAuthority.name == 'SERVICE_MANAGER') {
            $scope.redirect("companyList.html");
            $scope.menuList = [
                {
                    name: '公司列表',
                    url: '#/companyList',
                    menuId: 'company-List',
                    photobg: 'image/index-bg.png',
                    photoselect: 'image/index-select.png'
                },
                {
                    name: '用户列表',
                    url: '#/userList',
                    menuId: 'user-List',
                    photobg: 'image/user-bg.png',
                    photoselect: 'image/user-select.png'
                },
                {
                    name: '地图展示',
                    url: '#/mapshow',
                    menuId: 'map-Show',
                    photobg: 'image/index-bgmap.png',
                    photoselect: 'image/index-selectmap.png'
                },
                {
                    name: '设备种类',
                    url: '#/companySet',
                    menuId: 'company-Set',
                    photobg: 'image/set.png',
                    photoselect: 'image/set-select.png'
                }, {
                    name: '设备列表',
                    url: '#/unitlist',
                    menuId: 'unitlist',
                    photobg: 'image/userunit-bg.png',
                    photoselect: 'image/userunit-select.png'
                }, {
                    name: '硬件版本',
                    url: '#/version',
                    menuId: 'version',
                    photobg: 'image/version-bg.png',
                    photoselect: 'image/version-select.png'
                }
            ];
        } else {
            $scope.menuList = [
                {
                    name: '主 页',
                    url: '#/lou',
                    menuId: 'lou-Distribute',
                    photobg: 'image/index-bg.png',
                    photoselect: 'image/index-select.png'
                },
                {
                    name: '用户设备',
                    url: '#/userUnit',
                    menuId: 'user-Unit',
                    photobg: 'image/userunit-bg.png',
                    photoselect: 'image/userunit-select.png'
                },
                {
                    name: '统计报告',
                    url: '#/chartReport',
                    menuId: 'chart-Report',
                    photobg: 'image/tjbg-bg.png',
                    photoselect: 'image/tjbg-select.png'
                }
            ];
        }
        $scope.setmenuStyle($scope.menuList[0]);
    });
});

//悬浮内容展示
indexapp.directive('hover', [function () {
    return {
        restrict: 'A',
        link: function (scope, ele, attrs) {
            ele.bind('mouseover', function (e) {
                if ($(".previewContent:hidden").length > 0) {
                    $('.previewContent').hide();
                    $(this).parents('li').find(".previewContent").css('display', 'block').css('z-index', '999').fadeIn('slow');
                    // $(this).find(".previewContent").css('display', 'block').css('z-index', '99').fadeIn('slow');
                    scope.preViewPosition = {
                        left: (e.clientX + 15 + document.body.scrollLeft) + "px",
                        top: (e.clientY - 30 + document.body.scrollTop) + "px"
                    }
                    $(".previewContent").css('top', scope.preViewPosition.top);
                    $(".previewContent").css('left', scope.preViewPosition.left);
                }
            });
            ele.bind('mouseout', function (e) {
                $(".previewContent").fadeOut("fast");
            });
        }
    }
}]);

//个人资料
var controPersonData = function ($http, $scope, $location) {

    $scope.redirect = function (url) {
        $location.url(url);
    }
    //获取当前用户信息
    $scope.getUserListInfo = function () {
        $http.get(serviceHttp + 'api/rest/firm/person/mine/info').success(function (res) {
            $scope.getCurrenUser = res.data;
            var removeAlert = parseInt($scope.getCurrenUser.removeAlert);
        });
    }
    $scope.getUserListInfo();
    //修改登录密码初始化
    $scope.UpdateUserPwdInit = function () {
        $("#oldPwd").val("");
        $("#newPwd").val("");
        $("#sure-newPwd").val("");
    }
    //保存修改密码
    $scope.saveUpdateUserPwd = function () {
        var oldPwd = $("#oldPwd").val();
        var newPwd = $("#newPwd").val();
        var sure_newPwd = $("#sure-newPwd").val();
        if (oldPwd && newPwd && sure_newPwd) {
            if (newPwd !== sure_newPwd) {
                layer.msg("两次密码输入不一致，请重新输入！");
                return false;
            } else {
                $http.getData(serviceHttp + 'api/rest/operate/modify/password' + '?old=' + oldPwd + '&password=' + newPwd).success(function (res) {
                    if (res.error == 0) {
                        layer.msg("修改成功！");
                        deleteCookie("saveCookie", "/");
                        $("#saveCookie").removeAttr('checked');
                        setCookie("userName", "", 24, "/");
                        setCookie("userPwd", "", 24, "/");
                        $http.get(serviceHttp + 'api/rest/firm/person/mine/info').success(function (res) {
                            $scope.CurrentUser = res.data;
                            if (res.data.role.roleAuthority.name == 'SERVICE_BUSINESS' || res.data.role.roleAuthority.name == 'SERVICE_MANAGER') {
                                window.location.href = serviceHttp + 'inspect/Lab_login.html';
                            } else {
                                window.location.href = serviceHttp + 'inspect/Lab_login.html?company=' + $scope.CurrentUser.companyId;
                            }
                        });
                    } else {
                        layer.msg(res.message);
                    }
                }).error(function () {
                    layer.msg("原密码输入有误，请重新输入");
                });
            }
        } else {
            layer.msg('输入不合法!');
        }
    }

    var countdown = 60;
    $scope.getEmailCode = function () {
        if (countdown == -1) {
            $("#sendEmailCode").removeAttr("disabled");
            $("#sendEmailCode").val("获取验证码");
            return false;
        } else {
            $("#sendEmailCode").attr("disabled", true);
            // $("#sendEmailCode").val("重新发送(" + countdown + ")");
            countdown--;
        }
        setTimeout(function () {
            // $("#sendEmailCode").val("获取验证码");
        }, 1000)

        var email = $("#txt_email").val();//输入的邮箱；
        var emailPost = {
            email: email
        };
        function isEmail(str) {
            var reg = /^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/;
            return reg.test(str);
        }
        if(isEmail(email)){
            $http.post(serviceHttp + 'api/rest/operate/send/email/verify', JSON.stringify(emailPost)).success(function (res) {
                layer.msg(res.message);
            })
        }else{
            layer.msg("邮箱格式不正确")
        }
    }

    $scope.getMobileCode = function () {
        //  var val = $("#sendMobeliCode").val()
        if (countdown == -1) {
            $("#sendMobeliCode").removeAttr("disabled");
            // $("#sendMobeliCode").val("获取验证码");
            return false;

        } else {
            $("#sendMobeliCode").attr("disabled", true);
            // $("#sendMobeliCode").val("重新发送(" + countdown + ")");
            countdown--;
        }
        setTimeout(function () {
            // $scope.getMobileCode();
            $("#sendMobeliCode").val("获取验证码");
        }, 1000)
        var mobile = $("#txt_mobile").val();//输入的手机号；
        $http.getData(serviceHttp + 'api/rest/operate/send/mobile/verify/' + mobile).success(function (res) {
            //console.log(res.data);
            layer.msg(res.message);
        })
    }
    //绑定邮箱
    $scope.BindUserEmail = function () {
        var email = $("#txt_email").val();//输入的邮箱；
        var email_code = $("#txt_email_code").val();//输入的邮箱验证码；
        var postEmail = {
            email: email,
            verify: email_code
        }

        function isEmail(str) {
            var reg = /^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/;
            return reg.test(str);
        }

        if (email && email_code) {
            //判定邮箱格式
            if (isEmail(email)) {
                $http.post(serviceHttp + 'api/rest/operate/update/email', JSON.stringify(postEmail)).success(function (res) {
                    if (res.error == 0) {
                        layer.msg("绑定成功！");
                        $("#txt_email").val("");
                        $("#txt_email_code").val("");
                        $scope.getUserListInfo();
                    } else {
                        layer.msg("验证码输入有误！");
                    }
                }).error(function () {
                    layer.msg("绑定失败，请重新操作！");
                });
            } else {
                layer.msg("邮箱格式输入有误！");
            }
        } else {
            layer.msg("输入不合法！");
        }
    }
    //绑定手机号
    $scope.BindUserMobile = function () {
        var mobile = $("#txt_mobile").val();//输入的手机号；
        var mobile_code = $("#txt_mobile_code").val();//输入的手机验证码；
        //判定是否是手机号
        function checkPhone(strphone) {
            var reg = /^1(3|4|5|7|8)\d{9}$/;
            return reg.test(strphone);
        }

        if (mobile && mobile_code) {
            if (checkPhone(mobile)) {
                $http.getData(serviceHttp + 'api/rest/operate/update/mobile/' + mobile + '?verify=' + mobile_code).success(function (res) {
                    if (res.error == 0) {
                        layer.msg("绑定成功！");
                        $("#txt_mobile").val("");
                        $("#txt_mobile_code").val("");
                        $scope.getUserListInfo();
                    } else {
                        layer.msg("验证码输入有误！");
                    }
                }).error(function () {
                    layer.msg("绑定失败，请重新操作！");
                });
            } else {
                layer.msg("手机格式不合法！");
            }
        } else {
            layer.msg("输入不合法！");
        }
    }
    //保存用户信息修改
    $scope.saveUpdateUserInfo = function () {
        var name = $scope.getCurrenUser.userName == 'undefined' ? '' : $scope.getCurrenUser.userName;
        var jobNum = $scope.getCurrenUser.jobNum == 'undefined' ? '' : $scope.getCurrenUser.jobNum;
        var department = $scope.getCurrenUser.department == 'undefined' ? '' : $scope.getCurrenUser.department;
        var job = $scope.getCurrenUser.job == 'undefined' ? '' : $scope.getCurrenUser.job;
        // var telephone = $scope.getCurrenUser.telephone == 'undefined' ? '' : $scope.getCurrenUser.telephone;
        var removeAlert = $scope.getCurrenUser.removeAlert; //推送警报类型。0：允许（手机和邮箱）；1，邮箱；2，不允许
        if (name && jobNum && department && job) {
            $http.get(serviceHttp + 'api/rest/operate/update/user?userName=' + name + '&department=' + department + '&jobNum=' + jobNum + '&job=' + job + '&removeAlert=' + removeAlert).success(function (res) {

                layer.msg(res.message)
                $scope.getUserListInfo();

            });
        } else {
            layer.msg('输入不合法!');
        }
    }
}
indexapp.controller('personalDataController', controPersonData);

/*楼分布*/
var controlou = function ($http, $scope, $location, $routeParams) {
    //获取楼数据
    $scope.getLouList = function () {
        var enable = 1; //为1是所有可以使用的建筑，0为已删除的数据。
        $http.getData(serviceHttp + 'api/rest/firm/buildings/?enable=' + enable).success(function (res) {
            $scope.louDistribut = res.data.background;
            $scope.louData = res.data;
            $scope.louList = res.data.list;

            var vm = $scope.vm = {};
            vm.procssOnlineStyle = 'procssOnlineStyle';
            vm.procssOfflineStyle = 'procssOfflineStyle';
            vm.procssRedStyle = 'procssRedStyle';
            vm.procssYellowStyle = 'procssYellowStyle';

            var xAxis1 = ["online", "offline"];
            var value1 = 0;
            var option1 = [$scope.louData.online, $scope.louData.offline];
            for (var i = 0; i < option1.length; i++) {
                value1 += option1[i];
            }
            var title1 = "设备数量（" + value1 + "）";
            var bgcolor1 = ["#7ED321", "#FF5A5A"];

            creatZhuChart('canvasUnitPir', option1, xAxis1, title1, bgcolor1);

            var value2 = 0;
            var xAxis2 = ["黄色报警", "红色报警"]
            var option2 = [$scope.louData.lowAlert, $scope.louData.highAlert];
            for (var i = 0; i < option2.length; i++) {
                value2 += option2[i];
            }
            var title2 = '报警数量（' + value2 + '）';
            var bgcolor2 = ["#FEBF17", "#FF5A5A"];
            creatZhuChart('canvasWaringPir', option2, xAxis2, title2, bgcolor2);
        });
    }
    $scope.getLouList();
    $scope.redirect = function (url) {
        $location.url(url);
    }

}

indexapp.controller('louController', controlou);

/*层分布*/
var controceng = function ($http, $scope, $location, $routeParams) {

    $scope.getCengList = function () {
        var enable = 1; //为1是所有可以使用的建筑，0为已删除的数据。
        $scope.buildId = $routeParams["buildId"];
        $scope.louName = $routeParams["louName"];
        $http.get(serviceHttp + 'api/rest/firm/floors?buildId=' + $scope.buildId + '&enable=' + enable).success(function (res) {
            $scope.CengList = res.data.floors;
            $scope.CengData = res.data;
            var vm = $scope.vm = {};
            vm.procssOnlineStyle = 'procssOnlineStyle';
            vm.procssOfflineStyle = 'procssOfflineStyle';
            vm.procssRedStyle = 'procssRedStyle';
            vm.procssYellowStyle = 'procssYellowStyle';

            var xAxis1 = ["online", "offline"];
            var value1 = 0;
            var option1 = [$scope.CengData.online, $scope.CengData.offline];
            for (var i = 0; i < option1.length; i++) {
                value1 += option1[i];
            }
            var title1 = "设备数量（" + value1 + "）";
            var bgcolor1 = ["#7ED321", "#FF5A5A"];

            creatZhuChart('canvasUnitPir', option1, xAxis1, title1, bgcolor1);

            var value2 = 0;
            var xAxis2 = ["黄色报警", "红色报警"]
            var option2 = [$scope.CengData.lowAlert, $scope.CengData.highAlert];
            for (var i = 0; i < option2.length; i++) {
                value2 += option2[i];
            }
            var title2 = '报警数量（' + value2 + '）';
            var bgcolor2 = ["#FEBF17", "#FF5A5A"];
            creatZhuChart('canvasWaringPir', option2, xAxis2, title2, bgcolor2);
        });
    }
    $scope.getCengList();
    $scope.redirect = function (url) {
        $location.url(url);
    }
}
indexapp.controller('cengController', controceng);

/*室分布*/
var controshi = function ($http, $scope, $location, $routeParams) {
    $scope.getRoomList = function () {
        var enable = 1; //为1是所有可以使用的建筑，0为已删除的数据。
        $scope.floorName = $routeParams["floorName"];
        $scope.floorId = $routeParams["floorId"];
        $http.getData(serviceHttp + 'api/rest/firm/rooms?floorId=' + $scope.floorId + '&enable=' + enable).success(function (res) {
            $scope.roomList = res.data.roomList;
            $scope.roomData = res.data;
            //  console.log($scope.roomData);
            //   console.log($scope.roomList);
            var vm = $scope.vm = {};
            vm.procssOnlineStyle = 'procssOnlineStyle';
            vm.procssOfflineStyle = 'procssOfflineStyle';
            vm.procssRedStyle = 'procssRedStyle';
            vm.procssYellowStyle = 'procssYellowStyle';

            var xAxis1 = ["online", "offline"];
            var value1 = 0;
            var option1 = [$scope.roomData.online, $scope.roomData.offline];
            for (var i = 0; i < option1.length; i++) {
                value1 += option1[i];
            }
            var title1 = "设备数量（" + value1 + "）";
            var bgcolor1 = ["#7ED321", "#FF5A5A"];

            creatZhuChart('canvasUnitPir', option1, xAxis1, title1, bgcolor1);

            var value2 = 0;
            var xAxis2 = ["黄色报警", "红色报警"]
            var option2 = [$scope.roomData.lowAlert, $scope.roomData.highAlert];
            for (var i = 0; i < option2.length; i++) {
                value2 += option2[i];
            }
            var title2 = '报警数量（' + value2 + '）';
            var bgcolor2 = ["#FEBF17", "#FF5A5A"];
            creatZhuChart('canvasWaringPir', option2, xAxis2, title2, bgcolor2);
        });
    }
    $scope.getRoomList();

    $scope.redirect = function (url) {
        $location.url(url);
    }

}
indexapp.controller('shiController', controshi);

/*设备分布*/
var controunit = function ($http, $scope, $location, $routeParams) {

    $scope.getUnitInitList = function () {
        var enable = 1; //为1是所有可以使用的建筑，0为已删除的数据。
        $scope.roomId = $routeParams["roomId"];
        $http.getData(serviceHttp + 'api/rest/firm/devices?roomId=' + $scope.roomId + '&enable=' + enable).success(function (res) {
            $scope.unitData = res.data;
            $scope.unitList = res.data.deviceList;
            //  console.log($scope.unitList);
            //   console.log($scope.unitData);
            var xAxis1 = ["online", "offline"];
            var value1 = 0;
            var option1 = [$scope.unitData.online, $scope.unitData.offline];
            for (var i = 0; i < option1.length; i++) {
                value1 += option1[i];
            }
            var title1 = "设备数量（" + value1 + "）";
            var bgcolor1 = ["#7ED321", "#FF5A5A"];

            creatZhuChart('canvasUnitPir', option1, xAxis1, title1, bgcolor1);

            var value2 = 0;
            var xAxis2 = ["黄色报警", "红色报警"]
            var option2 = [$scope.unitData.lowAlert, $scope.unitData.highAlert];
            for (var i = 0; i < option2.length; i++) {
                value2 += option2[i];
            }
            var title2 = '报警数量（' + value2 + '）';
            var bgcolor2 = ["#FEBF17", "#FF5A5A"];
            creatZhuChart('canvasWaringPir', option2, xAxis2, title2, bgcolor2);
        });
    }
    $scope.getUnitInitList();

    //设备参数
    $scope.getRoomData = function () {
        $http.getData(serviceHttp + 'api/rest/room/current/data?roomId=' + $scope.roomId).success(function (res) {
            $scope.houseValue = res.data;
        });
    }
    $scope.getRoomData();

    $scope.redirect = function (url) {
        $location.url(url);
    }

}
indexapp.controller('unitController', controunit);

/*设备详情*/
//ng-model 中input文本框时间戳转换为日期格式
indexapp.directive('dateFormat', ['$filter', function ($filter) {
    var dateFilter = $filter('date');
    return {
        require: 'ngModel',
        link: function (scope, elm, attrs, ctrl) {

            function formatter(value) {
                return dateFilter(value, 'yyyy/MM/dd'); //format
            }

            function parser() {
                return ctrl.$modelValue;
            }

            ctrl.$formatters.push(formatter);
            ctrl.$parsers.unshift(parser);

        }
    };
}]);

var controunitDetails = function ($http, $scope, $location, $routeParams, $q, $interval) {

    $scope.unitId = $routeParams["unitId"];
    $scope.unitDeaTData = {};
    $scope.deviceId = '';
    $("#unitfileToUpload").unbind('change').change(function (e) {
        var file = e.target.files[0];
        $scope.preview(file, 'addunitphotoNew');
    });

    //修改设备详情--设备背景图
    $scope.updateUnitPhotoInfo = function () {
        var path = $("#unitfileToUpload").val();
        if (path) {
            $.ajaxFileUpload({
                url: serviceHttp + 'api/rest/file/change/picture/' + $scope.unitId,
                secureuri: false,
                fileElementId: 'unitfileToUpload',//file控件id
                success: function (res) {
                    $scope.getFloorList();
                }
            });
        }
    }

    //获取设备层列表
    $scope.getFloorList = function () {
        var enable = 1;
        $http.getData(serviceHttp + 'api/rest/firm/device?deviceId=' + $scope.unitId).success(function (res) {
            $scope.unitDeaTData = res.data;
            // $scope.selectedValue = res.data.manager.userName;
            $scope.currenyManagerId = res.data.manager.id;
            $scope.deviceId = res.data.id;
            $scope.unitdataFloors = res.data.deviceFloors;
            $scope.pangDingRoleInit();
        }).error(function () {
            // alert('系统已停止运行，请重新登录');
        });
    }

    //新增设备层初始化
    $scope.AddUnitCengInit = function () {
        $("#floorNum").val(""); //第几层
        $("#productType").val("");//样品类型
        $("#productNum").val(""); //样品数量
        $("#name").val("");//样品名称
        $("#effective_add").val("");//样品有效期
        //绑定选择科学家多选框
        $http.getData(serviceHttp + 'api/rest/firm/colleges/scientist').success(function (res) {
            $scope.selectScientist = " "; //当前选中的科学家
            $scope.selectScientistList = res.data;
        });
    }

    /*保存新增设备层信息*/
    $scope.addfloorInfo = function () {
        var type = 0; //0：新增；1：修改
        var floorNum = $scope.floorNum; //第几层
        var productType = $scope.productType; //样品类型
        var productNum = $scope.productNum;//样品数量
        var name = $scope.name; //样品名称rest/operate/device
        //  var effective = $scope.effective; //样品有效期
        var effective = $("#effective_add").val();  //样品有效期
        $http.getData(serviceHttp + 'api/rest/operate/device/floor/' + $scope.deviceId + '?type=' + type + '&floorNum=' + floorNum + '&name=' + name + '&productNum=' + productNum + '&effective=' + effective + '&productType=' + productType).success(function (res) {
            $scope.getFloorList();
        });
    }

    //根据角色判定；1，企业管理员，无删除设备层权限；2，科学家：有
    $scope.pangDingRoleInit = function () {
        //获取当前用户信息
        $http.getData(serviceHttp + 'api/rest/firm/person/mine/info').success(function (res) {
            $scope.currUserInfo = res.data;
            $scope.CurrentUserId = $scope.currUserInfo.id;
            console.log($scope.currUserInfo);
            if ($scope.currUserInfo.role.roleAuthority.name == 'FIRM_MANAGER') {
                $scope.hasShowManager = 1;
            }
        });
    }

    //修改设备层，初始化
    $scope.UpdateUnitFloorInfo = function (currentUnitFloor) {
        $scope.selectCurrUnitFloor = currentUnitFloor || this.unitfloor;
        $scope.CurrentFloorId = $scope.selectCurrUnitFloor.id;
        $scope.floorNum = $scope.selectCurrUnitFloor.floorNum;
        $scope.productType = $scope.selectCurrUnitFloor.type; //样品类型
        $scope.productNum = $scope.selectCurrUnitFloor.productNum;
        $scope.name = $scope.selectCurrUnitFloor.name;//样品名称
        $scope.effective = $scope.selectCurrUnitFloor.effective;
        //绑定选择科学家多选框
        $http.getData(serviceHttp + 'api/rest/firm/colleges/scientist').success(function (res) {
            $scope.selectScientist = " "; //当前选中的科学家
            $scope.selectScientistList = res.data;
            //  $scope.selectScientistList = [{id:1,userName:'A',teleophone:'18822320012'},{id:2,userName:'B',teleophone:'11122320012'}]
        });
        $scope.selected = [];
        $scope.selectedTags = [];

        var updateSelected = function (action, id, name) {
            if (action == 'add' && $scope.selected.indexOf(id) == -1) {
                $scope.selected.push(id);
                $scope.selectedTags.push(name);
            }
            if (action == 'remove' && $scope.selected.indexOf(id) != -1) {
                var idx = $scope.selected.indexOf(id);
                $scope.selected.splice(idx, 1);
                $scope.selectedTags.splice(idx, 1);
            }
        }

        $scope.updateSelection = function ($event, id) {
            var checkbox = $event.target;
            var action = (checkbox.checked ? 'add' : 'remove');
            updateSelected(action, id, checkbox.name);
        }

        $scope.isSelected = function (id) {
            return $scope.selected.indexOf(id) >= 0;
        }

    }

    /*修改层信息--保存*/
    $scope.updatefloorInfo = function () {
        var floorId = $scope.CurrentFloorId;
        var type = 1; //0：新增；1：修改
        var floorNum = $scope.floorNum; //第几层
        var productType = $scope.productType; //样品类型
        var productNum = $scope.productNum; //样品数量
        var name = $scope.name; //样品名称
        var effective = $scope.effective;//样品有效期
        $http.getData(serviceHttp + 'api/rest/operate/device/floor/' + $scope.deviceId + '?type=' + type + '&floorId=' + floorId + '&floorNum=' + floorNum + '&name=' + name + '&productNum=' + productNum + '&effective=' + effective + '&productType=' + productType).success(function (res) {
            $scope.getFloorList();
        });
    }

    //删除设备层信息
    $scope.deleteUnitCengInit = function (currentUnitFloor) {
        $scope.selectCurrUnitFloor = currentUnitFloor || this.unitfloor;
        $scope.CurrentFloorId = $scope.selectCurrUnitFloor.id;
    }

    //保存删除设备层信息
    $scope.SavedeleteUnitCengInfo = function () {
        //设备层Id
        var unitId = $scope.CurrentFloorId;
        $http.getData(serviceHttp + 'api/rest/operate/delete/device/floor/' + unitId).success(function (res) {
            $scope.getFloorList();
        });
    }
    $scope.getFloorList();

    var vm = $scope.vm = {};
    vm.style = 'procssBeatyStyle';

    //修改设备详情初始化
    $scope.updateUnitDetailInit = function () {
        $("#purchaseData").val();
        $("#maintainDate").val();
        //  $("#unit_xpoint").val( $scope.unitDeaTData.xPoint);
        // $("#unit_ypoint").val( $scope.unitDeaTData.yPoint);
        //绑定设备管理员下拉框
        $http.getData(serviceHttp + 'api/rest/firm/colleges/manager').success(function (res) {
            $scope.selectManager = " "; //当前选中的管理员
            $scope.selectManagerList = res.data;
            console.log($scope.selectManagerList);
        });

        /*
         * 绑定选择科学家多选框
         */
        //获取当前设备Id
        var spStr = location.hash.split("/");
        var divceId = spStr[spStr.length - 1];

        $http.getData(serviceHttp + 'api/rest/operate/is/device/sicentist/' + divceId).success(function (res) {
            $scope.selectScientist = " "; //当前选中的科学家
            $scope.selectScientistList = res.data;
        });
    }

    $scope.selectedRole = [];
    $scope.selectedTags = [];

    var updateSelected = function (action, id, name) {
        if (action == 'add' && $scope.selectedRole.indexOf(id) == -1) {
            $scope.selectedRole.push(id);
            $scope.selectedTags.push(name);
        }
        if (action == 'remove' && $scope.selectedRole.indexOf(id) != -1) {
            var idx = $scope.selectedRole.indexOf(id);
            $scope.selectedRole.splice(idx, 1);
            $scope.selectedTags.splice(idx, 1);
        }
    }

    $scope.updateSelection = function ($event, id) {
        var checkbox = $event.target;
        var action = (checkbox.checked ? 'add' : 'remove');
        updateSelected(action, id, checkbox.name);
    }

    $scope.isSelected = function (id) {
        return $scope.selectedRole.indexOf(id) >= 0;
    }
    //修改设备基本概况--保存
    $scope.updateUnitDetail = function () {
        var purchaseData = $("#purchaseData").val(); //购置日期
        var maintainDate = $("#maintainDate").val(); //最新维修时间
        var selected = $scope.selectManager.id == undefined ? '' : $scope.selectManager.id;
        var unit_xpoint = $("#unit_xpoint").val();
        var unit_ypoint = $("#unit_ypoint").val();
        var selectKXJ = $scope.selectedRole; //选择的科学家
        var name = $scope.unitDeaTData.name == undefined ? '' : $scope.unitDeaTData.name //设备名称
        var creator = $scope.unitDeaTData.creator == undefined ? '' : $scope.unitDeaTData.creator; //制造商
        var model = $scope.unitDeaTData.model == undefined ? '' : $scope.unitDeaTData.model;//设备品牌
        var maintain = $scope.unitDeaTData.maintain == undefined ? '' :$scope.unitDeaTData.maintain;//维护周期
        var flag = false;
        if ((purchaseData && purchaseData != "") && (maintainDate && maintainDate != "")) {
            if (purchaseData > maintainDate) {
                layer.msg("最新维修日期不能小于购置日期！");
                flag = false;
                $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
                return false;
            } else {
                flag = true;
            }

        }
        if (!unit_xpoint || unit_xpoint == "") {
            layer.msg("设备的横坐标不能为空");
            flag = false;
            $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
            return false;
        } else {
            //输入范围是否合法
            if (unit_xpoint >= 0 && unit_xpoint <= 780) {
                flag = true;
            } else {
                layer.msg("设备的横坐标输入不合法");
                flag = false;
                $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
                return false;
            }
        }
        if (!unit_xpoint || unit_xpoint == "") {
            layer.msg("设备的纵坐标不能为空");
            flag = false;
            $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
            return false;
        } else {
            //输入范围是否合法
            if (unit_ypoint >= 0 && unit_ypoint <= 315) {
                flag = true;
            } else {
                layer.msg("设备的纵坐标输入不合法");
                flag = false;
                $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
                return false;
            }
        }
        if (flag = true) {
            $(".btn-primary").attr("data-dismiss", "modal").attr("aria-hidden", "true");
            $http.getData(serviceHttp + 'api/rest/operate/device/' + $scope.unitDeaTData.id + '?name=' + name + '&creator=' + creator + '&maintainDate='
                + maintainDate + '&maintain='+ maintain + '&model=' + model + '&purchase=' + purchaseData + '&managerId=' + selected + '&scientist=' + selectKXJ
                + '&xPoint='+ unit_xpoint + '&yPoint='+ unit_ypoint).success(function (res) {
              $scope.getFloorList();
         });
      }
}

var echarts = new Array();
var renderTimer = undefined;
//获取设备信息
$http.getData(serviceHttp + 'api/rest/device/current/data?deviceId=' + $scope.unitId).success(function (res) {
    $scope.inspectData = res.data;
    $scope.inspects = res.data.list;
    var data = $scope.inspects;
    // console.log($scope.inspects);
    $scope.yiji_paramsBgColor = {"background-color": "#FFCC33"};
    $scope.erji_paramsBgColor = {"background-color": "#FFCC99"};
    $scope.biaozhun_paramsBgColor = {"background-color": "#00CC66"};

    clearTimeout(renderTimer);
    renderTimer = setTimeout(renderChart, 500);
    function formatDate(now) {
        var year = now.getYear();
        var month = now.getMonth() + 1;
        var date = now.getDate();
        var hour = now.getHours();
        var minute = now.getMinutes();
        var second = now.getSeconds();
        if (minute <= 9) {
            minute = '0' + minute;
        } else {
            minute = '' + minute;
        }
        if (second <= 9) {
            second = '0' + second;
        } else {
            second = '' + second;
        }
        //return   year+"-"+month+"-"+date+"   "+hour+":"+minute+":"+second;
        return "  " + month + "/" + date + " \n " + hour + ":" + minute;
    }

    // alert(formatDate(new Date(1230999938)));

    function renderChart() {
        echarts = new Array();
        var a = false;
        var linecolor = [];
        // console.log(data[0][0].deviceInspect.start);
        $('.canvasBox div').each(function () {
            var id = $(this).attr('id');
            a = true;
            if (id) {
                var flow = [];
                var index = id.substr(9);

                linecolor = ["#7ED321", "#FF5A5A", "#FF5A5A", "#FEBF17", "#FEBF17"];
                var data_result = {};
                data_result.id = "";
                data_result.result = [];
                // data_result.picResult = [];
                data_result.name = '检测数据';
                data_result.symbol = true;
                var line_result = [];

                var data_standard = {};
                data_standard.result = [];
                data_standard.name = '标准值';
                var line_standard = [];

                var data_lowUp = {};
                data_lowUp.result = [];
                // data_lowUp.name = '一级高值';
                data_lowUp.name = '高级报警';
                var line_lowUp = [];

                var data_lowDown = {};
                data_lowDown.result = [];
                // data_lowDown.name = '一级低值';
                data_lowDown.name = '高级报警';
                var line_lowDown = [];

                var data_highUp = {};
                data_highUp.result = [];
                // data_highUp.name = '二级高值';
                data_highUp.name = '低级报警';
                var line_highUp = [];

                var data_highDown = {};
                data_highDown.result = [];
                // data_highDown.name = '二级低值';
                data_highDown.name = '低级报警';
                var line_highDown = [];

                var charTitles = [];
                var charTitle = "";
                var xValue = [];
                if (data[index]) {
                    data[index].each(function (item, index) {
                        line_result.push(item.picResult);
                        // console.log(item.deviceInspect.inspectType.id);
                        line_result.id = item.deviceInspect.inspectType.id;
                        // line_standard.push(item.deviceInspect.standard);
                        line_lowUp.push(item.deviceInspect.lowUp);
                        line_lowDown.push(item.deviceInspect.lowDown);
                        line_highUp.push(item.deviceInspect.highUp);
                        line_highDown.push(item.deviceInspect.highDown);
                        xValue.push(formatDate(new Date(item.createDate)));
                        //formatDate(new Date(item.createDate))
                        charTitles.push(item.deviceInspect.name + '(单位：' + item.deviceInspect.inspectType.unit + ')');
                    })
                    data_result.id = line_result.id;
                    //if(line_result.id ==5 || line_result.id ==8){
                    //line_result.result[0]=='2'?'开':'关';
                    //   data_result.picResult = line_result.result[0];
                    // alert(data_result.picResult);
                    // }
                    data_result.result = line_result;
                    data_lowUp.result = line_lowUp;
                    data_lowDown.result = line_lowDown;
                    data_highUp.result = line_highUp;
                    data_highDown.result = line_highDown;
                }
                charTitle = charTitles[0];
                //flow.push(line_result, line_standard, line_lowUp, line_lowDown, line_highUp, line_highDown);
                flow.push(data_result, data_lowUp, data_lowDown, data_highUp, data_highDown);
                echarts.push(creatChart(id, flow, charTitle, linecolor, xValue));
                // console.log(data_result);
            }
        })
        clearTimeout(renderTimer);
        renderTimer = null;
        if (!a) {
            renderTimer = setTimeout(renderChart, 1000);
        }
    }
});

var timer = $interval(function () {
    function formatDate(now) {
        var year = now.getYear();
        var month = now.getMonth() + 1;
        var date = now.getDate();
        var hour = now.getHours();
        var minute = now.getMinutes();
        var second = now.getSeconds();
        if (minute <= 9) {
            minute = '0' + minute;
        } else {
            minute = '' + minute;
        }
        //return   year+"-"+month+"-"+date+"   "+hour+":"+minute+":"+second;
        return "  " + month + "/" + date + " \n " + hour + ":" + minute;
    }

    $http.getData(serviceHttp + 'api/rest/device/current/data?deviceId=' + $scope.unitId).success(function (res) {
        var data = res.data.list;
        for (var i = 0; i < echarts.length; i++) {
            var flow = [];
            var data_result = {};
            var linecolor = ["#7ED321", "#FF5A5A", "#FF5A5A", "#FEBF17", "#FEBF17"];
            data_result.result = [];
            // data_result.picResult = [];
            data_result.name = '检测数据';
            data_result.symbol = true;
            var line_result = [];

            var data_standard = {};
            data_standard.result = [];
            data_standard.name = '标准值';
            var line_standard = [];

            var data_lowUp = {};
            data_lowUp.result = [];
            data_lowUp.name = '高级高值';
            var line_lowUp = [];

            var data_lowDown = {};
            data_lowDown.result = [];
            data_lowDown.name = '高级低值';
            var line_lowDown = [];

            var data_highUp = {};
            data_highUp.result = [];
            data_highUp.name = '低级高值';
            var line_highUp = [];

            var data_highDown = {};
            data_highDown.result = [];
            data_highDown.name = '低级低值';
            var line_highDown = [];

            var charTitles = [];
            var charTitle = "";
            var xValue = [];
            if (data[i]) {
                data[i].each(function (item, index) {
                    line_result.push(item.picResult);
                    //    line_standard.push(item.deviceInspect.standard );
                    line_result.id = item.deviceInspect.inspectType.id;
                    line_lowUp.push(item.deviceInspect.lowUp);
                    line_lowDown.push(item.deviceInspect.lowDown);
                    line_highUp.push(item.deviceInspect.highUp);
                    line_highDown.push(item.deviceInspect.highDown);
                    charTitles.push(item.deviceInspect.name + '(单位：' + item.deviceInspect.inspectType.unit + ')');
                    xValue.push(formatDate(new Date(item.createDate)));
                })
                data_result.result = line_result;
                data_result.id = line_result.id;
                // if(line_result.id ==5 || line_result.id ==8){
                //     if(line_result.id ==5 || line_result.id ==8){
                //         data_result.result[0] == '2'?'开':'关';
                //         data_result.picResult = data_result.result[0];
                //     }
                // }
                // data_standard.result = line_standard;
                data_lowUp.result = line_lowUp;
                data_lowDown.result = line_lowDown;
                data_highUp.result = line_highUp;
                data_highDown.result = line_highDown;
            }
            charTitle = charTitles[0];
            // flow.push(line_result, line_standard, line_lowUp, line_lowDown, line_highUp, line_highDown);
            flow.push(data_result, data_lowUp, data_lowDown, data_highUp, data_highDown);
            updateChart(echarts[i], flow, charTitle, linecolor, xValue);
        }
    });

}, 3000);

$scope.devicePara = {};

//修改设备警报参数初始化
$scope.getDeviceAlterParameter = function () {

    $http.getData(serviceHttp + 'api/rest/operate/get/device/parameter/' + $scope.unitDeaTData.id).success(function (res) {
        $scope.devicePara = res.data;
    });
}

//保存--修改设备警报参数
$scope.updateAlertCSInfo = function () {
    var flag = false;
    if ($scope.devicePara && $scope.devicePara.list) {
        var length = $scope.devicePara.list.length;
        for (var i = 0; i < length; i++) {
            if ($scope.devicePara.list[i].id === 8){
                break;
            }
            var standard = parseInt($scope.devicePara.list[i].standard);
            var lowDown = parseInt($scope.devicePara.list[i].lowDown);
            var lowUp = parseInt($scope.devicePara.list[i].lowUp);
            var highDown = parseInt($scope.devicePara.list[i].highDown);
            var highUp = parseInt($scope.devicePara.list[i].highUp);
            //红色报警
            if (standard!=="" && lowDown!=="" && lowUp!=="" && highDown!=="" && highUp!=="") {
                if (highDown <= lowDown && lowDown <= standard && standard <= lowUp && lowUp <= highUp) {
                    flag = true;
                } else {
                    flag = false;
                    layer.msg("报警参数输入有误！");
                    $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
                    return false;

                }
            } else {
                layer.msg($scope.devicePara.list[i].name + "报警参数不能为空！");
                $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
                return false;
            }
        }
    }

    if (flag == true) {
        $(".btn-primary").attr("data-dismiss", "modal").attr("aria-hidden", "true");
        $http.post(serviceHttp + 'api/rest/operate/device/parameter/' + $scope.unitDeaTData.id, $scope.devicePara).success(function (res) {
            layer.msg(res.message)
            $scope.unitDeaTData = res.data;

        }).error(function (res) {
            layer.msg(res.message)
        });
    } else {
        $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
    }


}

$scope.redirect = function (url) {
    $location.url(url);
}
$scope.preview = function (file, imgId) {
    var img = $('#' + imgId),
        url = URL.createObjectURL(file);
    img.unbind();
    img.bind('load', function () {
        URL.revokeObjectURL(url);
    })
    img.attr('src', url);
}
/*下载文件*/
$scope.downloadFile = function (fileId) {
    window.parent.location.href = serviceHttp + 'api/rest/download/file/' + fileId;
}

//下载文件初始化
$scope.downLoadFileInit = function () {
    $scope.getFloorList();
}

/*删除文件*/
$scope.deletedFile = function (fileId) {
    var deviceId = $scope.unitId;
    $http.getData(serviceHttp + 'api/rest/operate/delete/file/' + fileId + '?deviceId=' + deviceId).success(function (res) {
        $scope.getFloorList();
    });
}

//上传文件初始化
$scope.uploadUnitFileInit = function () {

    $("#unitFileUploadToDevice").val('');
    $("#addFileUNITphotoNew").attr('src', '');

    $("#unitFileUploadToDevice").unbind('change').change(function (e) {
        var file = e.target.files[0];
        $scope.preview(file, 'addFileUNITphotoNew');
    });
}

/*上传文件*/
$scope.uploadDeviceFile = function () {
    var path = $("#unitFileUploadToDevice").val();
    if (path) {
        $.ajaxFileUpload({
            url: serviceHttp + 'api/rest/file/upload/device/file/' + $scope.unitId,
            secureuri: false,
            dataType:'json',
            fileElementId: 'unitFileUploadToDevice',//file控件id
            success: function (res) {
                // $scope.unitDeaTData = res.data;
                layer.msg(res.message)
                layer.msg("文件上传成功")
                $scope.getFloorList();
            }
        });
    }else{
        layer.msg("请上传文件")
    }
}
}
indexapp.controller('unitDetailController', controunitDetails);

/*用户列表*/
var controUserList = function ($http, $scope, $location) {

    $scope.total = 0;     // 总记录数
    $scope.pages = 0; // 总页数
    $scope.pageIndex = 0;	 //当前页
    $scope.range = function (start, end) {
        var ret = [];
        if (!end) {
            end = start;
            start = 0;
        }
        for (var i = start; i < end; i++) {
            ret.push(i);
        }
        return ret;
    };

    $scope.prevPage = function () {
        if ($scope.pageIndex > 0) {
            $scope.pageIndex--;
        }
        $scope.getUserList();
    };

    $scope.nextPage = function () {
        if ($scope.pageIndex < $scope.pages - 1) {
            $scope.pageIndex++;
        }
        $scope.getUserList();
    };

    $scope.setPage = function () {
        $scope.pageIndex = this.n;
        $scope.getUserList();
    };

    $scope.limit = 10;
    $scope.userName = "";
    $scope.mobile = "";
    $scope.jobNumber = "";
    $scope.currUserInfo = {};
    $scope.myrole = [];
    $scope.hasShowManager = 0;
    //获取用户列表
    $scope.getUserList = function () {
        //alert($scope.c_user.length);
        var start = $scope.pageIndex * $scope.limit;
        var limit = $scope.limit;
        var jobNumber = $scope.jobNumber;
        var userName = $scope.userName;
        var mobile = $scope.mobile;
        $http.getData(serviceHttp + 'api/rest/firm/employees' + '?start=' + start + '&limit=' + limit + '&userName=' + userName + '&mobile=' + mobile + '&jobNum=' + jobNumber).success(function (res) {
            $scope.total = res.data.total;
            if ($scope.limit > 0) {
                $scope.pages = parseInt($scope.total / $scope.limit) + ($scope.total % $scope.limit > 0 ? 1 : 0);
            }
            $scope.getUser = res.data.userList;
            console.log($scope.getUser);
            $(".btn-primary").attr("data-dismiss", "modal").attr("aria-hidden", "true");
        });
    }
    $scope.getUserList();

    //新增员工初始化
    $scope.getUserCompany = function () {
        $scope.newAccount = '';
        // $scope.selected.id = undefined;
        $scope.newUserName = '';
        $scope.newDepartment = '';
        $scope.newJobNum = '';
        $scope.newJob = '';
        $scope.myrole.FIRM_WORKER = "";
        $scope.myrole.FIRM_SCIENTIST = "";

        //获取当前用户信息
        $http.getData(serviceHttp + 'api/rest/firm/person/mine/info').success(function (res) {
            $scope.currUserInfo = res.data;
            if ($scope.currUserInfo.role.roleAuthority.name == "FIRM_MANAGER") {
                $scope.hasShowManager = 1;
            }
        });
    }

    $scope.getUserCompany();

    //绑定公司列表下拉框
    $scope.getCompanyList = function () {
        $http.getData(serviceHttp + 'api/rest/firm/query/all/company').success(function (res) {
            $scope.myCompanyList = res.data;
        });
    }

    //保存新增员工
    $scope.createUserByMe = function () {
        var newAccount = $scope.newAccount;
        // var companyId = $scope.selected.id;
        var userName = $scope.newUserName;
        var department = $scope.newDepartment;
        var jobNum = $scope.newJobNum;
        var job = $scope.newJob;
        //  var role = $scope.currUserInfo.role.roleAuthority;
        var role = $scope.myrole;
        var w = [];
        if (role.FIRM_WORKER == true && (role.FIRM_SCIENTIST == false || role.FIRM_SCIENTIST == undefined)) {
            w = ['FIRM_WORKER'];
        }
        if (role.FIRM_SCIENTIST == true && (role.FIRM_WORKER == false || role.FIRM_WORKER == undefined)) {
            w = ['FIRM_SCIENTIST'];
        }
        if (role.FIRM_WORKER == true && role.FIRM_SCIENTIST == true) {
            w = ['FIRM_WORKER', 'FIRM_SCIENTIST'];
        }

        if (newAccount && userName && department && jobNum && job) {
            $http.getData(serviceHttp + 'api/rest/operate/create/user/?name=' + newAccount + '&userName=' + userName + '&department=' + department + '&jobNum=' + jobNum + '&job=' + job + '&role=' + w).success(function (res) {

                if (res && res.error == 0) {
                    layer.msg(res.message)
                    $(".btn-primary").attr("data-dismiss", "modal").attr("aria-hidden", "true");
                    $scope.getUserList();
                } else {
                    layer.msg(res.message);
                    $(".btn-primary").attr("data-dismiss", "modal").attr("aria-hidden", "true");
                }
            });
        } else {
            layer.msg("输入信息不完整！");
            $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
        }

    }

    //删除员工初始化
    $scope.deleteUserInit = function (CurrUser) {
        $scope.Cuser = CurrUser || this.user;
        $http.getData(serviceHttp + 'api/rest/firm/take/over/colleges?userId=' + $scope.Cuser.id).success(function (res) {
            $scope.selectCurrent = "";
            $scope.selectManagerList = res.data; //当前选中的管理员
        });
    }
    //保存删除用户（交接）
    $scope.SaveDeleteUserHand = function () {
        var userId = $scope.Cuser.id;//当前用户的Id
        var takeId = $scope.selectCurrent.id; //要交接人的Id
        $http.getData(serviceHttp + 'api/rest/operate/delete/user/' + userId + '?takeId=' + takeId).success(function (res) {
            if (res.error == "1005") {
                layer.alert(res.message);
            } else {
                $scope.getUserList();
            }
        });
    }
    $scope.redirect = function (url) {
        $location.url(url);
    }

}
indexapp.controller('userListController', controUserList);

/*公司列表*/
var controCompanyList = function ($http, $scope, $location) {
    $scope.currentCompany = {};
    $http.getData(serviceHttp + 'api/rest/firm/query/all/company/').success(function (res) {
        $scope.allCompany = res.data;

    });
    //获取公司列表
    $scope.getCompanyList = function () {
        $scope.currentCompany = {};
        $http.getData(serviceHttp + 'api/rest/firm/query/all/company').success(function (res) {
            $scope.allCompany = res.data;
            $(".btn-primary").attr("data-dismiss", "modal").attr("aria-hidden", "true");
        });
        $("#addCompanyToUpload").unbind('change').change(function (e) {
            var file = e.target.files[0];
            $scope.preview(file, 'addCompanyPhotoNew');
        });
    }
    $scope.getCompanyList();

    //新增企业初始化
    $scope.addCompanyDialog = function () {
        $scope.currentCompany = {};
        $scope.currentCompany.manager = {};
        $("#addCompanyToUpload").val('');
        $("#addCompanyPhotoNew").attr('src', '');

        $("#CompanyName").val('');//企业名称
        $("#CompanyAddress").val('');//企业地址
        $("#CompanyEmail").val('');//企业邮箱
        $("#CompanyMobile").val('');//客服电话
        $("#AdminAccount").val('');//管理员账号
        $("#AdminName").val('');//管理员姓名
        $("#CompanyCoordinate").val('');
    }

    //保存新增企业
    $scope.addCompany = function () {
        var path = $("#addCompanyToUpload").val();
        // if($scope.currentCompany.manager.name == undefined){
        //     $scope.currentCompany.manager.name="";
        //     layer.msg("管理员账号不能为空");
        // }
        // if($scope.currentCompany.manager.userName == undefined){
        //     $scope.currentCompany.manager.userName="";
        // }
        var CompanyName = $("#CompanyName").val();//企业名称
        var CompanyAddress = $("#CompanyAddress").val();//企业地址
        var CompanyEmail = $("#CompanyEmail").val();//企业邮箱
        var CompanyMobile = $("#CompanyMobile").val();//客服电话
        var AdminAccount = $("#AdminAccount").val();//管理员账号
        var AdminName = $("#AdminName").val();//管理员姓名
        var CompanyCoordinate = $("#CompanyCoordinate").val();//企业坐标
        var flag = false;
        if (!CompanyName || CompanyName == "") {
            layer.msg("企业名称不能为空");
            flag = false;
            $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
            return false;
        } else {
            flag = true;
        }

        if (!CompanyAddress || CompanyAddress == "") {
            layer.msg("企业地址不能为空");
            flag = false;
            $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
            return false;
        } else {
            flag = true;
        }

        if (!CompanyEmail || CompanyEmail == "") {
            layer.msg("企业邮箱不能为空");
            flag = false;
            $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
            return false;
        } else {
            flag = true;
        }

        if (!AdminAccount || AdminAccount == "") {
            layer.msg("管理员账号不能为空");
            flag = false;
            $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
            return false;
        } else {
            flag = true;
        }

        if (!AdminName || AdminName == "") {
            layer.msg("管理员姓名不能为空");
            flag = false;
            $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
            return false;
        } else {
            flag = true;
        }

        if (!CompanyCoordinate || CompanyCoordinate == "") {
            layer.msg("企业坐标不能为空");
            flag = false;
            $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
            return false;
        } else {
            flag = true;
        }
        if (flag = true) {
            $(".btn-primary").attr("data-dismiss", "modal").attr("aria-hidden", "true");
            var pic;
            if(path){
                pic=0
            }else{
                pic=1
            }
            $.ajaxFileUpload({
                url: serviceHttp + 'api/rest/file/create/company' + '?name=' + CompanyName + '&address=' + CompanyAddress + '&email=' + CompanyEmail + '&telephone='
                + CompanyMobile + '&account=' + AdminAccount + '&userName=' + AdminName + '&location=' + CompanyCoordinate + '&pic=' + pic,
                secureuri: false,
                dataType: 'json',
                fileElementId: 'addCompanyToUpload',//file控件id
                success: function (data, status) {

                    if (data.error == 0) {
                        $scope.getCompanyList();
                        layer.msg(data.message)
                        $(".btn-primary").attr("data-dismiss", "modal").attr("aria-hidden", "true");
                    }

                }, error: function (data, status, e) {
                    console.log(e);
                    layer.msg("创建失败");
                    // layer.msg(status);
                }
            });
        } else {
            // $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
        }


    }

    //保存修改企业
    $scope.updateCompany = function () {
        var path = $("#updateCompanyToUpload").val();
        var pic;
        if(path){
            pic = 0;
        }else{
            pic = 1;
        }
        $.ajaxFileUpload({
            url: serviceHttp + 'api/rest/file/create/company' + '?id=' + $scope.currentCompany.id + '&name=' + $scope.currentCompany.name
            + '&address=' + $scope.currentCompany.address + '&email=' + $scope.currentCompany.email + '&telephone=' + $scope.currentCompany.telephone
            + '&account=' + $scope.currentCompany.manager.name + '&userName=' + $scope.currentCompany.manager.userName + '&location=' + $scope.currentCompany.location + '&pic=' + pic,
            secureuri: false,
            fileElementId: 'updateCompanyToUpload',//file控件id
            success: function (res) {
                // console.log($scope.currentCompany.manager.userName);
                $(".btn-primary").attr("data-dismiss", "modal").attr("aria-hidden", "true");
                $scope.getCompanyList();

            }, error: function (res, status, e) {
                console.log(e);
                layer.msg("修改失败，管理员账号已存在！");
                // layer.msg(status);
            }
        });

    }

    $scope.UpdateCurrentCompany = function (company) {

        $scope.currentCompany = company;
    }

    $scope.redirect = function (url) {
        $location.url(url);
    }

}
indexapp.controller('companyListController', controCompanyList);

/*设置*/
var controSetting = function ($http, $scope, $location) {

    $scope.showType = 1;
    $scope.buildId = "";
    $scope.floorId = "";
    $scope.roomList = [];
    $scope.roomId = "";
    $scope.setDate = [];
    $scope.preview = function (file, imgId) {
        var img = $('#' + imgId),
            url = URL.createObjectURL(file);
        img.unbind();
        img.bind('load', function () {
            URL.revokeObjectURL(url);
        })
        img.attr('src', url);
    }
    $scope.redirect = function (url) {
        $location.url(url);
    }


    //设备种类 -TAP
    $scope.showUnitType = function () {
        $scope.showType = 1;
        $scope.MyColor1 = {"background-color": "#2A2C38", "color": "#FFFFFF"};
        $scope.MyColor2 = {"background-color": "#FFFFFF", "color": "#2A2C38"};
        $scope.getUnitDate();
    }
    //楼层管理 -TAP
    $scope.showFloorManage = function () {
        $scope.showType = 2;
        $scope.normer_enable = 1;
        $scope.MyColor1 = {"background-color": "#2A2C38", "color": "#FFFFFF"};
        $scope.MyColor2 = {"background-color": "#FFFFFF", "color": "#2A2C38"};
        $scope.getlouList();
    }
    //楼层恢复 -TAP
    $scope.recoverFloor = function () {
        $scope.showType = 3;
        $scope.recover_enable = 0 || null;
        $scope.MyColor3 = {"background-color": "#2A2C38", "color": "#FFFFFF"};
        $scope.MyColor4 = {"background-color": "#FFFFFF", "color": "#2A2C38"};
        $scope.getlouList();
    }

    /*设备种类*/

    //获取设备种类列表
    $scope.getUnitDate = function () {
        var enable = 1;//是否被删除，当前默认为1.
        $http.getData(serviceHttp + 'api/rest/firm/device/types?enable=' + enable).success(function (res) {
            $scope.setDate = res.data;
            // console.log($scope.setDate);
        });
        $("#addUnitTypeToUpload").unbind('change').change(function (e) {
            var file = e.target.files[0];
            $scope.preview(file, 'addUnitTypePhotoNew');
        });
        $("#updateUnitTypeToUpload").unbind('change').change(function (e) {
            var file = e.target.files[0];
            $scope.preview(file, 'updateUnitTypePhotoNew');
        });


    }
    $scope.getUnitDate();
    //设置--新增设备弹出框初始化
    $scope.AddUnitTypeInit = function () {

        $("#addUnitTypeToUpload").val('');
        $("#addUnitTypePhotoNew").attr('src', '');
        // $(".btn-primary").attr("data-dismiss", "modal").attr("aria-hidden", "true");

        $http.getData(serviceHttp + 'api/rest/firm/query/inspect/type').success(function (res) {
            $scope.inspectUnitType = res.data;
            console.log($scope.inspectUnitType);
        });
    }

    //保存新增设备种类
    $scope.SaveAddUnitTypeInfo = function () {

        var path = $("#addUnitTypeToUpload").val();
        var UnitTypeName = $("#UnitTypeName").val();
        var flag = false;
        if (!UnitTypeName || UnitTypeName == "") {
            layer.msg("设备种类名称不能为空");
            flag = false;
            $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
            return false;
        } else {
            flag = true;
        }
        var f = false;
        if ($scope.inspectUnitType && $scope.inspectUnitType.list) {
            var length = $scope.inspectUnitType.list.length;
            var falseLenght = 0; //累计没选设备参数次数
            /*<!--begin-for-->*/
            for (var i = 0; i < length; i++) {
                if ($scope.inspectUnitType.list[i].chosed == false) {
                    falseLenght++;
                    f = false;
                    if (falseLenght >= 8) {
                        layer.msg("设备参数至少要填一项！");
                        flag = false;
                        $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
                    } else {
                        flag = true;
                    }
                } else {
                    f = true;
                    if ($scope.inspectUnitType.list[i].id === 8)  //设备种类-门状态（赋定值）
                    {
                        $scope.inspectUnitType.list[i].chosed = true;
                        $scope.inspectUnitType.list[i].standard = 1;//设备状态1:打开,2：关闭
                        $scope.inspectUnitType.list[i].lowDown = 0;
                        $scope.inspectUnitType.list[i].lowUp = 0;
                        $scope.inspectUnitType.list[i].highDown = 5;
                        $scope.inspectUnitType.list[i].highUp = 5;
                        break;
                    } else {
                        var standard = parseInt($scope.inspectUnitType.list[i].standard);
                        var lowDown = parseInt($scope.inspectUnitType.list[i].lowDown);
                        var lowUp = parseInt($scope.inspectUnitType.list[i].lowUp);
                        var highDown = parseInt($scope.inspectUnitType.list[i].highDown);
                        var highUp = parseInt($scope.inspectUnitType.list[i].highUp);
                        //红色报警
                        if (standard!=="" && lowDown!=="" && lowUp!=="" && highDown!=="" && highUp!=="") {
                            if (highDown <= lowDown && lowDown <= standard && standard <= lowUp && lowUp <= highUp) {
                                flag == true;
                            } else {
                                flag == false;
                                layer.msg($scope.inspectUnitType.list[i].name  + "报警参数输入有误！");
                                $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
                                return false;
                            }
                        } else {
                            layer.msg($scope.inspectUnitType.list[i].name + "报警参数不能为空！");
                            $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
                            return false;
                        }
                    }
                }
            }
            /*<!--end-for-->*/
        }

        if (flag == true) {
            $(".btn-primary").attr("data-dismiss", "modal").attr("aria-hidden", "true");
            $http.post(serviceHttp + 'api/rest/operate/deviceType/', $scope.inspectUnitType).success(function (res) {
                if (res && res.error == 0) {
                    $.ajaxFileUpload({
                        url: serviceHttp + 'api/rest/file/upload/deviceType/icon/' + res.data.id,
                        secureuri: false,
                        fileElementId: 'addUnitTypeToUpload',//file控件id
                        success: function (res, status) {
                            $(".btn-primary").attr("data-dismiss", "modal").attr("aria-hidden", "true");
                            $scope.getUnitDate();
                        }
                    });
                } else {
                    layer.msg(res.message);
                }
            }).error(function (res, status) {
                // layer.msg("警报参数输入不合法！");
                $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
                return false;
            });
        } else {
            // layer.msg("警报参数输入有误！");
            $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
            return false;
        }
    }

    //修改设备弹出框初始化
    $scope.UpdateUnitTypeInit = function (id) {
        $("#updateUnitTypePhotoNew").attr("src","");
        $("#updateUnitTypeToUpload").val("");
        $http.getData(serviceHttp + 'api/rest/firm/device/type/request/' + id).success(function (res) {
            $scope.currentDeviceTypeReq = res.data;
        }).error(function (res) {
            alert("error")
        });
    }

    //保存修改设备种类
    $scope.SaveUpdateUnitTypeInfo = function () {
        var UnitTypeName = $("#up_UnitTypeName").val();
        var flag = false;
        if (!UnitTypeName || UnitTypeName == "") {
            layer.msg("设备种类名称不能为空");
            flag = false;
            $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
            return false;

        } else {
            flag = true;
        }
        if ($scope.currentDeviceTypeReq && $scope.currentDeviceTypeReq.list) {
            var length = $scope.currentDeviceTypeReq.list.length;
            var f = false;
            for (var i = 0; i < length; i++) {
                if ($scope.currentDeviceTypeReq.list[i].id === 8){
                    break;
                }
                var standard = parseInt($scope.currentDeviceTypeReq.list[i].standard);
                var lowDown = parseInt($scope.currentDeviceTypeReq.list[i].lowDown);
                var lowUp = parseInt($scope.currentDeviceTypeReq.list[i].lowUp);
                var highDown = parseInt($scope.currentDeviceTypeReq.list[i].highDown);
                var highUp = parseInt($scope.currentDeviceTypeReq.list[i].highUp);
                //红色报警
                if (standard!=="" && lowDown!=="" && lowUp!=="" && highDown!=="" && highUp!=="") {
                    if (highDown <= lowDown && lowDown <= standard && standard <= lowUp && lowUp <= highUp) {
                        flag = true;
                    } else {
                        flag = false;
                        layer.msg("报警参数输入有误！");
                        $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
                        return false;

                    }
                } else {
                    layer.msg($scope.inspectUnitType.list[i].name + "报警参数不能为空！");
                    $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
                    return false;
                }
            }
        }
        if (flag == true) {
            $(".btn-primary").attr("data-dismiss", "modal").attr("aria-hidden", "true");
            $http.post(serviceHttp + 'api/rest/operate/deviceType/', $scope.currentDeviceTypeReq).success(function (res) {
                var path = $("#updateUnitTypeToUpload").val();
                $.ajaxFileUpload({
                    url: serviceHttp + 'api/rest/file/upload/deviceType/icon/' + res.data.id,
                    secureuri: false,
                    fileElementId: 'updateUnitTypeToUpload',//file控件id
                    success: function (data, status) {
                        layer.msg(res.message);
                        $scope.getUnitDate();
                    }
                });
            }).error(function (data) {
                layer.msg("加载有误，请稍候再试！");
            });
        } else {
            $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
        }
    }
    //删除设备弹出框初始化
    $scope.deleteUnitTypeInit = function (currUnitType) {
        $scope.selectCurrUnitTypeId = currUnitType.id || this.set.id;
    }

    //保存删除设备
    $scope.SavedeleteUnitTypeInfo = function () {
        var typeId = $scope.selectCurrUnitTypeId;//设备类型Id
        var enable = 0;
        $http.getData(serviceHttp + 'api/rest/operate/manager/device/type/' + typeId + '?enable=' + enable).success(function (res) {
            $scope.getUnitDate();

        });
    }

    /*楼层管理*/

    //获取楼列表
    $scope.getlouList = function () {
        var enable = null;
        //楼层管理
        if ($scope.showType === 2) {
            enable = $scope.normer_enable;
        }
        //楼层恢复
        if ($scope.showType === 3) {
            enable = $scope.recover_enable;
        }
        $(".btn-primary").attr("data-dismiss", "modal").attr("aria-hidden", "true");
        $http.getData(serviceHttp + 'api/rest/firm/buildings?enable=' + enable).success(function (res) {
            $scope.louData = res.data;
            //列表背景初始化
            if (res.data && res.data.list) {
                for (var i = 0; i < res.data.list.length; i++) {
                    $scope.louData.list[i].selected = 0;
                }
                $scope.selectLou = $scope.louData.list[0];
            } else {
                $scope.selectLou = null;
            }
            $scope.selectedCurrentlou($scope.selectLou);

            //新增--楼--背景分布图
            $("#loufileToUpload").unbind('change').change(function (e) {
                var file = e.target.files[0];
                $scope.preview(file, 'addlouphotoNew');
            });
            //修改--楼--背景分布图
            $("#updateloufileToUpload").unbind('change').change(function (e) {
                var file = e.target.files[0];
                $scope.preview(file, 'updatelouphotoNew');
            });

        });
    }
    $scope.getlouList();

    //选中当前楼
    $scope.selectedCurrentlou = function (currLou) {

        $scope.selectLou = currLou || this.lou;
        if ($scope.louData && $scope.louData.list.length > 0) {
            for (var i = 0; i < $scope.louData.list.length; i++) {
                $scope.louData.list[i].selected = 0;
            }
        }
        $scope.currEditImg = "image/edit-bg.png";
        $scope.currDelImg = "image/del-bg.png";
        $scope.selectEditImg = "image/edit-select.png";
        $scope.selectDelImg = "image/del-select.png";
        $scope.currRecoverImg = "image/recover_bg.png";
        $scope.selectRecoverImg = "image/recover_select.png";
        $scope.libgStyle = {"background-color": "#FFFFFF"};
        $scope.liColorStyle = {"color": "#A7A7A7"};
        //选中当前列表，改变背景颜色和字体颜色
        currLou.selected = 1;// color: #A7A7A7
        currLou.selectedCurrentBg = {"background-color": "#37BCFF"};
        currLou.selectedCurrentColor = {"color": "#FFFFFF"};
        $scope.buildId = !$scope.selectLou ? "" : $scope.selectLou.id;
        $scope.selectCeng = null;
        $scope.selectShi = null;
        $scope.selectUnit = null;
        $scope.getCengList();
        $scope.getShiList();
        $scope.getUnitList();
    }

    //新增楼弹出框初始化
    $scope.AddlouInit = function () {
        $("#lou_name").val("");
        $("#lou_xpoint").val("");
        $("#lou_ypoint").val("");
        $("#loufileToUpload").val('');
        $("#addlouphotoNew").attr('src', '');
    }

    //保存--新增楼--的值
    $scope.SaveAddlouInfo = function () {
        var path = $("#loufileToUpload").val();
        var type = 0;// 0:新增；1:修改
        var lou_name = $("#lou_name").val();
        var lou_xpoint = $("#lou_xpoint").val();
        var lou_ypoint = $("#lou_ypoint").val();
        var flag = false;
        if (!lou_name || lou_name == "") {
            layer.msg("楼名称不能为空");
            flag = false;
            $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
            return false;
        } else {
            flag = true;
        }

        if (!lou_xpoint || lou_xpoint == "") {
            layer.msg("楼的横坐标不能为空");
            flag = false;
            $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
            return false;
        } else {
            //输入范围是否合法
            if (lou_xpoint >= 0 && lou_xpoint <= 780) {
                flag = true;
            } else {
                layer.msg("楼的横坐标输入不合法");
                flag = false;
                $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
                return false;
            }
        }

        if (!lou_ypoint || lou_ypoint == "") {
            layer.msg("楼的纵坐标不能为空");
            flag = false;
            $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
            return false;
        } else {
            //输入范围是否合法
            if (lou_ypoint >= 0 && lou_ypoint <= 315) {
                flag = true;
            } else {
                layer.msg("楼的纵坐标输入不合法");
                flag = false;
                $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
                return false;
            }
        }

        if (flag == true) {
            var pic;
            if(path){
                pic = 0;
            }else{
                pic = 1;
            }
            $.ajaxFileUpload({
                url: serviceHttp + 'api/rest/file/create/building?name=' + lou_name + '&xpoint=' + lou_xpoint + '&ypoint=' + lou_ypoint + '&type=' + type + '&pic=' + pic,
                secureuri: false,
                fileElementId: 'loufileToUpload',//file控件id
                dataType: 'json',
                success: function (res) {
                    if (res && res.error == 0) {
                        $(".btn-primary").attr("data-dismiss", "modal").attr("aria-hidden", "true");
                        $scope.getlouList();
                    } else {
                        layer.msg(res.message);
                    }
                },
                error: function (res, status, e) {
                    layer.msg(status);
                }
            });
        } else {
            $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
        }
    }

    //修改当前楼弹出框初始化
    $scope.UpdatelouInit = function (currentLou) {
        var selectCurrentLou = currentLou || this.lou;
        console.log(selectCurrentLou);
        $scope.lou_name = selectCurrentLou.name;
        $scope.lou_xpoint = selectCurrentLou.xpoint;
        $scope.lou_ypoint = selectCurrentLou.ypoint;

    }

    //保存--修改楼--的值
    $scope.SaveUpdatelouInfo = function () {
        if (!$scope.selectLou) {
            return;
        }
        var path = $("#updateloufileToUpload").val();
        var buildId = $scope.selectLou.id;
        //alert(buildId);
        var type = 1;// 0:新增；1:修改
        var lou_name = $scope.lou_name;
        var lou_xpoint = $scope.lou_xpoint;
        var lou_ypoint = $scope.lou_ypoint;
        var flag = false;
        if (!lou_name || lou_name == "") {
            layer.msg("楼名称不能为空");
            flag = false;
            $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
            return false;
        } else {
            flag = true;
        }

        if (!lou_xpoint || lou_xpoint == "") {
            layer.msg("楼的横坐标不能为空");
            flag = false;
            $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
            return false;
        } else {
            //输入范围是否合法
            if (lou_xpoint >= 0 && lou_xpoint <= 780) {
                flag = true;
            } else {
                layer.msg("楼的横坐标输入不合法");
                flag = false;
                $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
                return false;
            }
        }

        if (!lou_ypoint || lou_ypoint == "") {
            layer.msg("楼的纵坐标不能为空");
            flag = false;
            $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
            return false;
        } else {
            //输入范围是否合法
            if (lou_ypoint >= 0 && lou_ypoint <= 315) {
                flag = true;
            } else {
                layer.msg("楼的纵坐标输入不合法");
                flag = false;
                $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
                return false;
            }
        }
        if (flag == true) {
            var pic;
            if(path){
                pic = 0;
            }else{
                pic = 1;
            }
            $.ajaxFileUpload({
                url: serviceHttp + 'api/rest/file/create/building?name=' + lou_name + '&xpoint=' + lou_xpoint + '&ypoint=' + lou_ypoint + '&type=' + type + '&buildId=' + buildId + '&pic=' + pic,
                secureuri: false,
                fileElementId: 'updateloufileToUpload',//file控件id
                dataType: 'json',
                success: function (res) {
                    if (res && res.error == 0) {
                        $(".btn-primary").attr("data-dismiss", "modal").attr("aria-hidden", "true");
                        $scope.getlouList();
                    } else {
                        layer.msg(res.message);
                    }
                },
                error: function (res, status, e) {
                    layer.msg(status);
                }
            });
        } else {
            $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
        }
    }

    //删除楼
    $scope.SaveDeletelouInfo = function () {
        if (!$scope.selectLou) {
            return;
        }
        var enable = 0;
        var build = $scope.selectLou.id;
        $http.get(serviceHttp + 'api/rest/operate/manager/build/' + build + '?enable=' + enable).success(function (res) {
            if (res.error == 0) {
                layer.msg("删除成功");
                $scope.getlouList();
            } else {
                layer.msg(res.message);
            }

        });
    }

    //获取层列表
    $scope.getCengList = function () {
        if (!$scope.selectLou) {
            $scope.CengList = [];
            return;
        }
        var buildId = $scope.selectLou.id;
        var enable = null;
        //楼层管理
        if ($scope.showType === 2) {
            enable = $scope.normer_enable;
        }
        //楼层恢复
        if ($scope.showType === 3) {
            enable = $scope.recover_enable;
        }
        $http.getData(serviceHttp + 'api/rest/firm/floors?buildId=' + buildId + '&enable=' + enable).success(function (res) {
            $scope.cengData = res.data;
            if (res.data && res.data.floors) {
                for (var i = 0; i < res.data.floors.length; i++) {
                    $scope.cengData.floors[i].selected = 0;
                }
                $scope.selectCeng = res.data.floors[0];
            } else {
                $scope.selectCeng = null;
            }
            $scope.selectedCurrentCeng($scope.selectCeng);

            $("#cengfileToUpload").unbind('change').change(function (e) {
                var file = e.target.files[0];
                $scope.preview(file, 'addcengphotoNew');
            });

            $("#updateCengfileToUpload").unbind('change').change(function (e) {
                var file = e.target.files[0];
                $scope.preview(file, 'updateCengphotoNew');
            });
        });
    }

    //选中当前层
    $scope.selectedCurrentCeng = function (currCeng) {
        $scope.selectCeng = currCeng || this.ceng;
        $scope.floorId = !$scope.selectCeng ? "" : $scope.selectCeng.id;
        $scope.selectShi = null;
        $scope.currEditImg = "image/edit-bg.png";
        $scope.currDelImg = "image/del-bg.png";
        $scope.selectEditImg = "image/edit-select.png";
        $scope.selectDelImg = "image/del-select.png";
        if ($scope.cengData && $scope.cengData.floors) {
            for (var i = 0; i < $scope.cengData.floors.length; i++) {
                $scope.cengData.floors[i].selected = 0;
            }
        }
        $scope.libgStyle = {"background-color": "#FFFFFF"};
        $scope.liColorStyle = {"color": "#A7A7A7"};
        //选中当前列表，改变背景颜色和字体颜色
        currCeng.selected = 1;
        currCeng.selectedCurrentBg = {"background-color": "#37BCFF"};
        currCeng.selectedCurrentColor = {"color": "#FFFFFF"};
        $scope.getShiList();
        $scope.getUnitList();
    }

    //新增层弹出框初始化
    $scope.AddCengInit = function () {
        $("#ceng_name").val("");
        $("#ceng_xpoint").val("");
        $("#ceng_ypoint").val("");
        $("#cengfileToUpload").val('');
        $("#addcengphotoNew").attr('src', '');
    }

    //保存--新增层--的值
    $scope.SaveAddCengInfo = function () {
        if (!$scope.selectLou) {
            return;
        }
        var path = $("#cengfileToUpload").val();
        var type = 0;// 0:新增；1:修改
        var buildId = this.selectLou.id;
        var ceng_name = $("#ceng_name").val();
        var ceng_xpoint = $("#ceng_xpoint").val();
        var ceng_ypoint = $("#ceng_ypoint").val();
        var flag = false;
        if (!ceng_name || ceng_name == "") {
            layer.msg("层名称不能为空");
            flag = false;
            $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
            return false;
        } else {
            flag = true;
        }

        if (!ceng_xpoint || ceng_xpoint == "") {
            layer.msg("层的横坐标不能为空");
            flag = false;
            $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
            return false;
        } else {
            //输入范围是否合法
            if (ceng_xpoint >= 0 && ceng_xpoint <= 780) {
                flag = true;
            } else {
                layer.msg("层的横坐标输入不合法");
                flag = false;
                $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
                return false;
            }
        }

        if (!ceng_ypoint || ceng_ypoint == "") {
            layer.msg("层的纵坐标不能为空");
            flag = false;
            $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
            return false;
        } else {
            //输入范围是否合法
            if (ceng_ypoint >= 0 && ceng_ypoint <= 315) {
                flag = true;
            } else {
                layer.msg("层的纵坐标输入不合法");
                flag = false;
                $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
                return false;
            }
        }
        if (flag == true) {
            var pic;
            if(path){
                pic = 0;
            }else{
                pic = 1;
            }
            $.ajaxFileUpload({
                url: serviceHttp + 'api/rest/file/create/floor?name=' + ceng_name + '&xpoint=' + ceng_xpoint + '&ypoint=' + ceng_ypoint + '&type=' + type + '&buildId=' + $scope.buildId + '&pic=' + pic,
                secureuri: false,
                fileElementId: 'cengfileToUpload',//file控件id
                dataType: 'json',
                success: function (res) {
                    if (res && res.error == 0) {
                        $scope.getCengList();
                        $(".btn-primary").attr("data-dismiss", "modal").attr("aria-hidden", "true");
                    } else {
                        layer.msg(res.message);
                    }
                },
                error: function (res, status, e) {
                    layer.msg(status);
                }
            });
        } else {
            $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
        }
    }

    //修改当前层初始化弹出框
    $scope.UpdateCengInit = function (currentCeng) {
        var selectCurrentCeng = currentCeng || this.ceng;
        $scope.ceng_name = selectCurrentCeng.name;
        $scope.ceng_xpoint = selectCurrentCeng.xpoint;
        $scope.ceng_ypoint = selectCurrentCeng.ypoint;
    }

    //保存--修改层--的值
    $scope.SaveUpdateCengInfo = function () {
        if (!this.selectLou || !this.selectCeng) {
            return;
        }
        var path = $("#updateCengfileToUpload").val();
        var buildId = this.selectLou.id;
        var floorId = this.selectCeng.id;
        var type = 1;// 0:新增；1:修改
        var flag = false;
        var ceng_name = $scope.ceng_name;
        var ceng_xpoint = $scope.ceng_xpoint;
        var ceng_ypoint = $scope.ceng_ypoint;
        if (!ceng_name || ceng_name == "") {
            layer.msg("楼名称不能为空");
            flag = false;
            $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
            return false;
        } else {
            flag = true;
        }

        if (!ceng_xpoint || ceng_xpoint == "") {
            layer.msg("层的横坐标不能为空");
            flag = false;
            $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
            return false;
        } else {
            //输入范围是否合法
            if (ceng_xpoint >= 0 && ceng_xpoint <= 780) {
                flag = true;
            } else {
                layer.msg("层的横坐标输入不合法");
                flag = false;
                $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
                return false;
            }
        }

        if (!ceng_ypoint || ceng_ypoint == "") {
            layer.msg("楼的纵坐标不能为空");
            flag = false;
            $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
            return false;
        } else {
            //输入范围是否合法
            if (ceng_ypoint >= 0 && ceng_ypoint <= 315) {
                flag = true;
            } else {
                layer.msg("层的纵坐标输入不合法");
                flag = false;
                $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
                return false;
            }
        }
        if (flag == true) {
            var pic;
            if(path){
                pic = 0;
            }else{
                pic = 1;
            }
            $.ajaxFileUpload({
                url: serviceHttp + 'api/rest/file/create/floor?name=' + ceng_name + '&xpoint=' + ceng_xpoint + '&ypoint=' + ceng_ypoint + '&type=' + type + '&buildId=' + buildId + '&floorId=' + floorId + '&pic=' + pic,
                secureuri: false,
                fileElementId: 'updateCengfileToUpload',//file控件id
                dataType: 'json',
                success: function (res, status) {
                    if (res && res.error == 0) {
                        $scope.getCengList();
                        $(".btn-primary").attr("data-dismiss", "modal").attr("aria-hidden", "true");
                    } else {
                        layer.msg(res.message);
                    }
                },
                error: function (res, status, e) {
                    layer.msg(status);
                }
            });
        } else {
            $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
        }

    }

    //删除层
    $scope.DeleteCengInfo = function () {
        if (!$scope.selectLou || !$scope.selectCeng) {
            return;
        }
        var enable = 0;
        //var buildId = this.selectLou.id;
        var floorId = $scope.selectCeng.id;
        $http.get(serviceHttp + 'api/rest/operate/manager/floor/' + floorId + '?enable=' + enable).success(function (res) {
            if (res.error == 0) {
                layer.msg("删除成功");
                $scope.getCengList();
            } else {
                layer.msg(res.message);
            }
        });
    }

    //获取室列表
    $scope.getShiList = function () {
        if (!$scope.selectCeng) {
            $scope.roomList = [];
            return;
        }
        var buildId = $scope.buildId;
        var floorId = $scope.selectCeng.id;
        var enable = null;
        //楼层管理
        if ($scope.showType === 2) {
            enable = $scope.normer_enable;
        }
        //楼层恢复
        if ($scope.showType === 3) {
            enable = $scope.recover_enable;
        }
        $http.getData(serviceHttp + 'api/rest/firm/rooms?buildId=' + buildId + '&floorId=' + floorId + '&enable=' + enable).success(function (res) {
            $scope.roomData = res.data;
            $scope.roomList = res.data.roomList;

            if (res.data && res.data.roomList) {
                for (var i = 0; i < res.data.roomList.length; i++) {
                    $scope.roomList[i].selected = 0;
                }
                $scope.selectShi = $scope.roomList[0];
            } else {
                $scope.selectShi = null;
            }
            $scope.selectedCurrentShi($scope.selectShi);

            $("#AddshifileToUpload").unbind('change').change(function (e) {
                var file = e.target.files[0];
                $scope.preview(file, 'AddshiphotoNew');
            });

            $("#updateShifileToUpload").unbind('change').change(function (e) {
                var file = e.target.files[0];
                $scope.preview(file, 'updateShiphotoNew');
            });
        });
    }

    //选中当前室
    $scope.selectedCurrentShi = function (currShi) {
        $scope.selectShi = currShi || this.shi;
        $scope.roomId = !$scope.selectShi ? "" : $scope.selectShi.id;
        $scope.selectUnit = null;
        if ($scope.roomList && $scope.roomList.length > 0) {
            for (var i = 0; i < $scope.roomList.length; i++) {
                $scope.roomList[i].selected = 0;
            }
        }
        $scope.currEditImg = "image/edit-bg.png";
        $scope.currDelImg = "image/del-bg.png";
        $scope.selectEditImg = "image/edit-select.png";
        $scope.selectDelImg = "image/del-select.png";
        $scope.libgStyle = {"background-color": "#FFFFFF"};
        $scope.liColorStyle = {"color": "#A7A7A7"};
        //选中当前列表，改变背景颜色和字体颜色
        currShi.selected = 1;
        currShi.selectedCurrentBg = {"background-color": "#37BCFF"};
        currShi.selectedCurrentColor = {"color": "#FFFFFF"};
        $scope.getUnitList();
    }

    //新增室弹出框初始化
    $scope.AddshiInit = function () {
        $("#shi_name").val("");
        $("#shi_xpoint").val("");
        $("#shi_ypoint").val("");
        $("#AddshifileToUpload").val('');
        $("#AddshiphotoNew").attr('src', '');
    }

    //保存--新增室--的值
    $scope.SaveAddShiInfo = function () {
        if (!$scope.selectCeng) {
            return;
        }
        var path = $("#AddshifileToUpload").val();
        var type = 0;// 0:新增；1:修改
        var floorId = this.selectCeng.id;
        var shi_name = $("#shi_name").val();
        var shi_xpoint = $("#shi_xpoint").val();
        var shi_ypoint = $("#shi_ypoint").val();
        var flag = false;
        if (!shi_name || shi_name == "") {
            layer.msg("室名称不能为空");
            flag = false;
            $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
            return false;
        } else {
            flag = true;
        }

        if (!shi_xpoint || shi_xpoint == "") {
            layer.msg("室的横坐标不能为空");
            flag = false;
            $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
            return false;
        } else {
            //输入范围是否合法
            if (shi_xpoint >= 0 && shi_xpoint <= 780) {
                flag = true;
            } else {
                layer.msg("室的横坐标输入不合法");
                flag = false;
                $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
                return false;
            }
        }

        if (!shi_ypoint || shi_ypoint == "") {
            layer.msg("室的纵坐标不能为空");
            flag = false;
            $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
            return false;
        } else {
            //输入范围是否合法
            if (shi_ypoint >= 0 && shi_ypoint <= 315) {
                flag = true;
            } else {
                layer.msg("室的纵坐标输入不合法");
                flag = false;
                $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
                return false;
            }
        }
        if (flag == true) {
            var pic;
            if(path){
                pic = 0;
            }else{
                pic = 1;
            }
            $.ajaxFileUpload({
                url: serviceHttp + 'api/rest/file/create/room?name=' + shi_name + '&xpoint=' + shi_xpoint + '&ypoint=' + shi_ypoint + '&type=' + type + '&floorId=' + floorId + '&pic=' + pic,
                secureuri: false,
                fileElementId: 'AddshifileToUpload',//file控件id
                dataType: 'json',
                success: function (res) {
                    if (res && res.error == 0) {
                        $(".btn-primary").attr("data-dismiss", "modal").attr("aria-hidden", "true");
                        $scope.getShiList();
                    } else {
                        layer.msg(res.message);
                    }
                },
                error: function (res, status, e) {
                    layer.msg(status);
                }
            });
        } else {
            $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
        }
    }

    //修改室初始化弹出框
    $scope.UpdateShiInit = function (currentShi) {
        var selectCurrentShi = currentShi || this.shi;
        //console.log(selectCurrentShi);
        $scope.shi_name = selectCurrentShi.name;
        $scope.shi_xpoint = selectCurrentShi.xPoint;
        $scope.shi_ypoint = selectCurrentShi.yPoint;
    }

    //保存--修改室--的值
    $scope.SaveUpdateShiInfo = function () {
        if (!$scope.selectCeng || !$scope.selectShi) {
            return;
        }
        var path = $("#updateShifileToUpload").val();
        var type = 1;// 0:新增；1:修改
        var floorId = this.selectCeng.id;
        var roomId = this.selectShi.id;
        var shi_name = $scope.shi_name;
        var shi_xpoint = $scope.shi_xpoint;
        var shi_ypoint = $scope.shi_ypoint;
        var flag = false;
        if (!shi_name || shi_name == "") {
            layer.msg("室名称不能为空");
            flag = false;
            $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
            return false;
        } else {
            flag = true;
        }

        if (!shi_xpoint || shi_xpoint == "") {
            layer.msg("室的横坐标不能为空");
            flag = false;
            $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
            return false;
        } else {
            //输入范围是否合法
            if (shi_xpoint >= 0 && shi_xpoint <= 780) {
                flag = true;
            } else {
                layer.msg("室的横坐标输入不合法");
                flag = false;
                $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
                return false;
            }
        }

        if (!shi_ypoint || shi_ypoint == "") {
            layer.msg("室的纵坐标不能为空");
            flag = false;
            $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
            return false;
        } else {
            //输入范围是否合法
            if (shi_ypoint >= 0 && shi_ypoint <= 315) {
                flag = true;
            } else {
                layer.msg("室的纵坐标输入不合法");
                flag = false;
                $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
                return false;
            }
        }

        if (flag == true) {
            var pic;
            if(path){
                pic = 0;
            }else{
                pic = 1;
            }
            $.ajaxFileUpload({
                url: serviceHttp + 'api/rest/file/create/room?name=' + shi_name + '&xpoint=' + shi_xpoint + '&ypoint=' + shi_ypoint + '&type=' + type + '&floorId=' + floorId + '&roomId=' + roomId + '&pic=' + pic,
                secureuri: false,
                fileElementId: 'updateShifileToUpload',//file控件id
                dataType: 'json',
                success: function (res) {
                    if (res && res.error == 0) {
                        $(".btn-primary").attr("data-dismiss", "modal").attr("aria-hidden", "true");
                        $scope.getShiList();
                    } else {
                        layer.msg(res.message);
                    }
                },
                error: function (res, status, e) {
                    layer.msg(status);
                }
            });
        } else {
            $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
        }
    }

    //删除室
    $scope.DeleteShiInfo = function () {
        if (!$scope.selectLou || !$scope.selectCeng || !$scope.selectShi) {
            return;
        }
        var enable = 0;
        var build = this.selectLou.id;
        var floorId = $scope.selectCeng.id;
        var roomId = $scope.selectShi.id;
        $http.get(serviceHttp + 'api/rest/operate/manager/room/' + roomId + '?enable=' + enable).success(function (res) {
            if (res.error == 0) {
                layer.msg("删除成功");
                $scope.getShiList();
            } else {
                layer.msg(res.message);
            }
        });
    }

    //获取设备列表
    $scope.getUnitList = function () {
        if (!$scope.selectShi) {
            $scope.deviceList = [];
            return;
        }
        var roomId = $scope.selectShi.id;
        var enable = null;
        //楼层管理
        if ($scope.showType === 2) {
            enable = $scope.normer_enable;
        }
        //楼层恢复
        if ($scope.showType === 3) {
            enable = $scope.recover_enable;
        }
        $http.getData(serviceHttp + 'api/rest/firm/devices?roomId=' + roomId + '&enable=' + enable).success(function (res) {
            // $scope.unitData = res.data;
            $scope.deviceList = res.data.deviceList;

            if (res.data && res.data.deviceList) {
                for (var i = 0; i < res.data.deviceList.length; i++) {
                    $scope.deviceList[i].selected = 0;
                }
                $scope.selectUnit = res.data.deviceList[0];
            } else {
                $scope.selectUnit = null;
            }
            $scope.selectedCurrentUnit($scope.selectUnit);

            $("#AddunitfileToUpload").unbind('change').change(function (e) {
                var file = e.target.files[0];
                $scope.preview(file, 'AddunitphotoNew');
            });
        });
    }

    //选中当前设备
    $scope.selectedCurrentUnit = function (currUnit) {
        $scope.selectUnit = currUnit || this.unit;
        $scope.unitId = !$scope.selectUnit ? "" : $scope.selectUnit.id;
        if ($scope.deviceList && $scope.deviceList.length > 0) {
            for (var i = 0; i < $scope.deviceList.length; i++) {
                $scope.deviceList[i].selected = 0;
            }
        }
        $scope.libgStyle = {"background-color": "#FFFFFF"}; //背景色
        $scope.liColorStyle = {"color": "#A7A7A7"}; //字体背景色
        //选中当前列表，改变背景颜色和字体颜色
        currUnit.selected = 1;
        currUnit.selectedCurrentBg = {"background-color": "#37BCFF"};//选中背景色
        currUnit.selectedCurrentColor = {"color": "#FFFFFF"};//选中字体颜色

    }

    //新增设备弹出框初始化
    $scope.AddUnitInit = function () {
        $scope.unit_name = "";
        $scope.unit_code = "";
        $scope.unit_xpoint = "";
        $scope.unit_ypoint = "";
        $scope.unit_monitorCode = "";
        // $scope.selectManager.id = null;
        $("#unitfileToUpload").val('');
        $("#addunitphotoNew").attr('src', '');

        //绑定设备种类下拉框
        $scope.getUnitTypeBySelectList = function () {
            var enable = 1; //是否被删除，当前默认为1.
            $http.getData(serviceHttp + 'api/rest/firm/device/types?enable=' + enable).success(function (res) {
                $scope.selected = " ";//当前选中的设备类型
                $scope.selectUnit = res.data;
                //    console.log($scope.selectUnit);
            });
        }
        //绑定设备管理员下拉框
        $scope.getUnitManagerByselectList = function () {
            $http.getData(serviceHttp + 'api/rest/firm/colleges/manager').success(function (res) {
                $scope.selectManager = " "; //当前选中的管理员
                $scope.selectManagerList = res.data;
                //    console.log($scope.selectManagerList);
            });
        }
        //绑定选择科学家多选框
        $scope.getUnitScientistByselectList = function () {
            $http.getData(serviceHttp + 'api/rest/firm/colleges/scientist').success(function (res) {
                $scope.selectScientist = " "; //当前选中的科学家
                $scope.selectScientistList = res.data;
            });
        }
        $scope.selectedRole = [];
        $scope.selectedTags = [];

        var updateSelected = function (action, id, name) {
            if (action == 'add' && $scope.selectedRole.indexOf(id) == -1) {
                $scope.selectedRole.push(id);
                $scope.selectedTags.push(name);
            }
            if (action == 'remove' && $scope.selectedRole.indexOf(id) != -1) {
                var idx = $scope.selectedRole.indexOf(id);
                $scope.selectedRole.splice(idx, 1);
                $scope.selectedTags.splice(idx, 1);
            }
        }

        $scope.updateSelection = function ($event, id) {
            var checkbox = $event.target;
            var action = (checkbox.checked ? 'add' : 'remove');
            updateSelected(action, id, checkbox.name);
        }

        $scope.isSelected = function (id) {
            return $scope.selectedRole.indexOf(id) >= 0;
        }
        $scope.getUnitTypeBySelectList();
        $scope.getUnitManagerByselectList();
        $scope.getUnitScientistByselectList();
    }

    //保存--新增设备
    $scope.SaveAddUnitInfo = function () {
        var path = $("#AddunitfileToUpload").val();//可空
        var typeId = $scope.selected.id == undefined ? '' : $scope.selected.id;//所选设备种类Id
        var roomId = this.selectShi.id;
        var unit_code = $scope.unit_code;
        var unit_name = $scope.unit_name;
        var unit_xpoint = $scope.unit_xpoint;
        var unit_ypoint = $scope.unit_ypoint;
        var unit_managerId = $scope.selectManager.id == undefined ? '' : $scope.selectManager.id;  //设备管理员
        var unit_monitorCode = $scope.unit_monitorCode; //终端编号
        var selectScientist = $scope.selectedRole;//选中的科学家列表
        var flag = false;
        if (!unit_name || unit_name == "") {
            layer.msg("请填写设备名称");
            flag = false;
            return false;
        } else {
            flag = true;
        }

        if (!unit_code || unit_code == "") {
            layer.msg("请填写设备编号");
            flag = false;
            return false;
        } else {
            flag = true;
        }

        if (typeId == "") {
            layer.msg("请选择设备种类");
            flag = false;
            return false;
        } else {
            flag = true;
        }

        if (!unit_xpoint || unit_xpoint == "") {
            layer.msg("请填写设备所在的横坐标");
            flag = false;
            return false;
        } else {
            //输入范围是否合法
            if (unit_xpoint >= 0 && unit_xpoint <= 780) {
                flag = true;
            } else {
                layer.msg("设备的横坐标输入不合法");
                flag = false;
                $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
                return false;
            }
        }

        if (!unit_ypoint || unit_ypoint == "") {
            layer.msg("请填写设备所在的纵坐标");
            flag = false;
            return false;
        } else {
            //输入范围是否合法
            if (unit_ypoint >= 0 && unit_ypoint <= 315) {
                flag = true;
            } else {
                layer.msg("设备的纵坐标输入不合法");
                flag = false;
                $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
                return false;
            }
        }

        if (unit_monitorCode == "") {
            layer.msg("请填写终端编号");
            flag = false;
            return false;
        } else {
            flag = true;
        }
        if (flag == true) {
            var pic;
            if(path){
                pic = 0;
            }else{
                pic = 1;
            }
            // unitfileToUpload
            $.ajaxFileUpload({
                url: serviceHttp + "api/rest/file/create/device?roomId=" + roomId + "&typeId=" + typeId + "&code=" + unit_code + "&managerId=" + unit_managerId + "&xPoint=" + unit_xpoint + "&yPoint=" + unit_ypoint + "&name=" + unit_name + "&monitorCode=" + unit_monitorCode + '&scientist=' + selectScientist + '&pic=' + pic,
                secureuri: false,
                fileElementId: 'AddunitfileToUpload',//file控件id
                dataType: 'json',
                success: function (res) {
                    $(".btn-primary").attr("data-dismiss", "modal").attr("aria-hidden", "true");
                    $scope.getUnitList();
                },
                error: function (res, status, e) {
                    console.log(e);
                    layer.msg("设备已经存在，无法重复添加,请重新填写！");
                    // layer.msg(status);
                }
            });
        } else {
            $(".btn-primary").removeAttr("data-dismiss", "modal").removeAttr("aria-hidden", "true");
        }

    }
    //修改设备
    // $scope.UpdateUnitInit = function (currentUnit) {
    //     var selectCurrentUnit = currentUnit || this.unit;
    //     //console.log(selectCurrentShi);
    //    // $scope.shi_name = selectCurrentUnit.name;
    //     $scope.unit_xpoint = selectCurrentUnit.xPoint;
    //     $scope.unit_ypoint = selectCurrentUnit.yPoint;
    //     //绑定选择科学家多选框
    //     $http.getData(serviceHttp + 'api/rest/firm/colleges/scientist').success(function (res) {
    //         $scope.selectScientist = " "; //当前选中的科学家
    //         $scope.selectScientistList = res.data;
    //     });
    // }
    //保存修改设备
    // $scope.SaveUpdateUnitInfo = function () {
    //
    // }
    /*楼层恢复*/

    //lou恢复
    $scope.RecoverlouInfo = function (currLou) {
        $scope.recoverCurrLou = currLou || this.lou;
        var buildId = $scope.recoverCurrLou.id;
        currLou.enable = 1;//恢复到楼层管理中
        $http.getData(serviceHttp + 'api/rest/operate/manager/build/' + buildId + '?enable=' + currLou.enable).success(function (res) {
            //    console.log(res.data.message);
        });
    }
    //ceng恢复
    $scope.RecoverCengInfo = function (currCeng) {
        $scope.recoverCurrCeng = currCeng || this.ceng;
        var floorId = $scope.recoverCurrCeng.id;
        currCeng.enable = 1;//恢复到楼层管理中
        $http.getData(serviceHttp + 'api/rest/operate/manager/floor/' + floorId + '?enable=' + currCeng.enable).success(function (res) {
            //    console.log(res.data.message);
        });
    }
    //室恢复
    $scope.RecoverShiInfo = function (currShi) {
        $scope.recoverCurrLou = currShi || this.shi;
        var roomId = $scope.recoverCurrLou.id;
        currShi.enable = 1;//恢复到楼层管理中
        $http.getData(serviceHttp + 'api/rest/operate/manager/room/' + roomId + '?enable=' + currShi.enable).success(function (res) {
            //    console.log(res.data.message);
        });
    }
    //unit恢复
    $scope.RecoverUnitInfo = function (currUnit) {
        $scope.recoverCurrLou = currUnit || this.unit;
        var deviceId = $scope.recoverCurrLou.id;
        currUnit.enable = 1;//恢复到楼层管理中
        $http.getData(serviceHttp + 'api/rest/operate/manager/device/' + deviceId + '?enable=' + currUnit.enable).success(function (res) {
            //   console.log(res.data.message);
        });
    }
}
indexapp.controller('settingController', controSetting);

/*用户设备*/
var controuserUnit = function ($http, $scope, $location) {

    $scope.total = 0;     // 总记录数
    $scope.pageTotal = 0; // 总页数
    $scope.pageIndex = 0;	 //当前页
    $scope.range = function (start, end) {
        var ret = [];
        if (!end) {
            end = start;
            start = 0;
        }
        for (var i = start; i < end; i++) {
            ret.push(i);
        }
        return ret;
    };

    $scope.prevPage = function () {
        if ($scope.pageIndex > 0) {
            $scope.pageIndex--;
        }
        $scope.getUserUnitList();
    };

    $scope.nextPage = function () {
        if ($scope.pageIndex < $scope.pageTotal - 1) {
            $scope.pageIndex++;
        }
        $scope.getUserUnitList();
    };

    $scope.setPage = function () {
        $scope.pageIndex = this.n;
        $scope.getUserUnitList();
    };

    $scope.limit = 10;
    $scope.code = "";// 设备编号
    $scope.unitName = ""; //设备名称
    $scope.code = "";
    $scope.unitZDcode = "";//终端编号
    $scope.CurrentUnitId = "";//当前设备Id

    $scope.getUnitType = function () {
        // var selectedVal = $scope.selectedVal.id;
        //绑定设备种类下拉框
        var enable = 1;
        $http.getData(serviceHttp + 'api/rest/firm/device/types?enable=' + enable).success(function (res) {
            $scope.getUnitDate = res.data;
            // console.log($scope.setDate);
        });
    }
    //用户设备列表
    $scope.getUserUnitList = function () {
        var start = $scope.pageIndex * $scope.limit;
        var limit = $scope.limit;
        var code = $scope.code; // 设备编号
        var unitType = $scope.selectUnit == undefined ? "" : $scope.selectUnit; //设备种类
        var name = $scope.unitName; //设备名称
        var monitorCode = $scope.unitZDcode //设备终端编号
        var enable = 1;//设备是否被删除，用户设备列表中可以写死为1
        $http.getData(serviceHttp + 'api/rest/firm/manager/devices' + '?start=' + start + '&limit=' + limit + '&code=' + code + '&name=' + name + '&monitorCode=' + monitorCode + '&unitType=' + unitType + '&enable=' + enable).success(function (res) {
            $scope.total = res.data.total;
            if ($scope.limit > 0) {
                $scope.pageTotal = parseInt($scope.total / $scope.limit) + ($scope.total % $scope.limit > 0 ? 1 : 0);
            }
            // $scope.getUserUnit = res.data;
            $scope.getUserDevice = res.data.devices;
            //console.log($scope.getUserDevice);
        });
    }

    //删除设备初始化
    $scope.deleteUnitInit = function (currUnit) {
        $scope.selectcurrUnit = this.unit || currUnit; //当前设备
        $scope.CurrentUnitId = $scope.selectcurrUnit.id; //当前的设备Id
    }

    //删除用户设备
    $scope.SavedeleteUnitInfo = function () {
        var deviceId = $scope.CurrentUnitId;
        $http.getData(serviceHttp + 'api/rest/operate/manager/device/' + deviceId + '?enable=0').success(function (res) {
            $scope.getUserUnitList();
            // if(res.error==0){
            //    alert(res.message);
            // }
        });
    }
    $scope.redirect = function (url) {
        $location.url(url);
    }
    $scope.getUnitType();
    $scope.getUserUnitList();

}
indexapp.controller('userUnitController', controuserUnit);

/*平台业务员*/
var controPlateformUser = function ($http, $scope, $location) {

    $scope.redirect = function (url) {
        $location.url(url);
    }
}
indexapp.controller('plateformUserController', controPlateformUser);

/*统计报告*/
var chartReportInfo = function ($http, $scope, $location) {

    $scope.redirect = function (url) {
        $location.url(url);
    }

}
indexapp.controller('chartReportController', chartReportInfo);

/*地图展示*/
var mapshowInfo = function ($http, $scope, $location) {

    $scope.redirect = function (url) {
        $location.url(url);
    }

}
indexapp.controller('mapshowController', mapshowInfo);

/*版本硬件更新*/
var versionUpdate = function ($http, $scope, $location) {

    $scope.insertVersion = {};
    // 获取版本信息列表
    $scope.getVersionList = function () {
        $http.getData(serviceHttp + '/api/rest/firm//service/get/versions/').success(function (res) {
            $scope.HardWare = res.data;
            var downfileid = $scope.HardWare.id;
        });
    }
    $scope.getVersionList();


    //新增版本初始化
    $scope.versionSaveDialog = function () {
        $scope.insertVersion = {};
        $scope.insertVersion.code_first = '';
        $scope.insertVersion.code_second = '';
        $scope.insertVersion.code_third = '';
        $scope.insertVersion.code_forth = '';
        $scope.insertVersion.message = '';
        $("input[type='radio']").checked = false;
    }

    $scope.versionSave = function () {
        var path = $("#versionToUpload").val();  //判断是否上传文件
        if (path) {
            $.ajaxFileUpload({
                url: serviceHttp + '/api/rest/file/create/device/version' + '?name=' + $scope.insertVersion.name
                + '&code_first=' + $scope.insertVersion.code_first + '&code_second=' + $scope.insertVersion.code_second + '&code_third='
                + $scope.insertVersion.code_third + '&code_forth=' + $scope.insertVersion.code_forth + '&message=' + $scope.insertVersion.message + '&type=' + $scope.insertVersion.type,
                secureuri: false,
                dataType: 'json',
                fileElementId: 'versionToUpload',//file控件id
                success: function (res) {
                    if (res.error == 0) {
                        layer.msg(res.message)

                    } else {
                        layer.msg(res.message)
                    }
                    $scope.getVersionList();
                },
                error: function () {
                }
            });
        } else {
            layer.msg("请上传文件");
        }
    }

    // 版本说明弹窗框
    $scope.versionImprint = function () {
        var id = this.version.id;
        $http.get(serviceHttp + '/api/rest/operate/device/version/explain/' + id).success(function (res) {
            $scope.versionmessage = res.data;
            var messageabout = $scope.versionmessage.message;
            if (messageabout == undefined || messageabout == "") {
                layer.msg("暂无版本说明")
            } else {
            }
            ;

        }).error(function () {
            layer.msg("获取失败");
        });

    }

    // 下载文件
    $scope.versionFile = function (downfileid) {
        window.parent.location.href = serviceHttp + 'api/rest/download/device/version/' + downfileid;
    }

    $scope.redirect = function (url) {
        $location.url(url);
    }
}
indexapp.controller('versionController', versionUpdate);


/*设备列表*/
var unitlistInfo = function ($http, $scope, $location) {
    $scope.total = 0;     // 总记录数
    $scope.pageTotal = 0; // 总页数
    $scope.pageIndex = 0;	 //当前页
    var checkid = [];//多选数组
    var newcheckid = [];//多选去重数组
    $scope.range = function (start, end) {
        var ret = [];
        if (!end) {
            end = start;
            start = 0;
        }
        for (var i = start; i < end; i++) {
            ret.push(i);
        }
        return ret;
    };
    $scope.prevPage = function () {
        if ($scope.pageIndex > 0) {
            $scope.pageIndex--;
            $scope.selectAll=false;
            checkid = [];
        }
        $scope.getUnitList();
    };

    $scope.nextPage = function () {
        if ($scope.pageIndex < $scope.pageTotal - 1) {
            $scope.pageIndex++;
            $scope.selectAll=false;
            checkid = [];
        }
        $scope.getUnitList();
    };

    $scope.setPage = function () {
        $scope.pageIndex = this.n;
        $scope.selectAll=false;
        $scope.getUnitList();
        checkid = [];
    };

    $scope.limit = 10;
    $scope.code = "";// 设备编号
    $scope.companyName = ""; //公司名称
    $scope.code = "";
    $scope.unitZDcode = "";//终端编号
    $scope.CurrentUnitId = "";//当前设备Id

    //用户设备列表
    $scope.getUnitList = function () {
        var start = $scope.pageIndex * $scope.limit;
        var limit = $scope.limit;
        var code = $scope.code; // 设备编号
        var companyName = $scope.companyName;
        var monitorCode = $scope.unitZDcode //设备终端编号
        var enable = 1;//设备是否被删除，用户设备列表中可以写死为1
        $http.getData(serviceHttp + 'api/rest/firm/service/device' + '?start=' + start + '&limit=' + limit + '&code=' + code + '&serchCompanyName=' + companyName + '&monitorCode=' + monitorCode + '&enable=' + enable).success(function (res) {
            $scope.total = res.data.total;
            if ($scope.limit > 0) {
                $scope.pageTotal = parseInt($scope.total / $scope.limit) + ($scope.total % $scope.limit > 0 ? 1 : 0);
            }
            $scope.getdeviceslist=null;
            $scope.getdeviceslist = res.data.devices;

        });
    }


    //全选
    $scope.selectAll=false;

    $scope.all= function () {
        checkid = [];
        $scope.selectAll = !$scope.selectAll;
        if($scope.selectAll == true){
                for(var i=0;i<$scope.getdeviceslist.length;i++){
                    $scope.getdeviceslist[i].checked = $scope.selectAll;
                    var k = $scope.getdeviceslist[i].id;
                    checkid.push(k);
                }

        }else{

                for(var i=0;i<$scope.getdeviceslist.length;i++){
                    $scope.getdeviceslist[i].checked = $scope.selectAll;
                    var k = $scope.getdeviceslist[i].id;
                    checkid.pop(k);
                }
        }

    };

    // 多选获取设备id值
    $scope.radiochosse = function () {
        var ss = !this.shebei.checked;
        var id = this.shebei.id;

        if(ss == true){
            checkid.push(id);
        }else{
            checkid.pop(id);
        }
    }



    //全选版本更新初始化窗口

    $scope.multiversion= function () {
        // 数组去重
        newcheckid = [];
        $scope.checkversionid = "";
        for(var j= 0; j<checkid.length; j++){
            var iteam = checkid[j];
            if($.inArray(iteam,newcheckid)== -1){
                newcheckid.push(iteam);
            }
        }
        if(!!newcheckid && newcheckid.length == 0 ){
            layer.msg("请勾选设备")
            $("#Versionupdate").removeAttr("data-toggle", "modal");
        }
        else{
            $("#Versionupdate").attr("data-toggle", "modal");
        }
        $http.getData(serviceHttp + 'api/rest/operate/select/device/version').success(function (res) {
            $scope.versionlist = res.data;
        }).error(function () {

        })
    };


    // 保存全选版本更新内容
    $scope.ALLversionchoose = function () {

        var id = $scope.checkversionid;
        $http.get(serviceHttp + '/api/rest/operate/update/multi/device/version/' + id + '?multiversion=' + newcheckid).success(function (res) {
            if (res.error == "1005") {
                layer.msg(res.message)
            } else {
            };
            checkid = [];
            newcheckid = [];
            $scope.selectAll=false;
            $scope.getUnitList();
        }).error(function () {
            layer.msg("请选择需要更新的版本")
            $scope.selectAll=false;
            $scope.getUnitList();
        })


    }



    //修改终端编号初始化
    $scope.unitsaveDialog = function () {
        $scope.newunitnumber = "";
        $scope.unitnumber = this.shebei.monitorDevice.number;
    }

    // 保存修改的终端编号
    $scope.unitsave = function () {
        var number = $scope.unitnumber;
        if ($scope.newunitnumber == "") {
            layer.msg("终端编号不能为空")
        } else {
            $http.get(serviceHttp + '/api/rest/operate/device/code/' + number + '?newNumber=' + $scope.newunitnumber).success(function (res) {
                if (res.error == 0) {
                    layer.msg("修改成功");
                } else {
                    layer.msg(res.message);
                }
                $scope.getUnitList();
            }).error(function () {
                layer.msg("保存失败");
            });
        }
    }

    //修改漂零值初始化
    $scope.zerosaveDialog = function () {
        var id = this.shebei.id;

        $http.getData(serviceHttp + 'api/rest/operate/set/zero/' + id).success(function (res) {
            $scope.unitzerodata = res.data;
        });
    }

    // 保存修改漂零值
    $scope.zerosave = function () {
        $scope.unitchangezero = this.unitzero.zero;
        var id = this.unitzero.id;
        this.unitzero.correctionValue =this.unitzero.originalValue - this.unitzero.zero;
        $http.get(serviceHttp + '/api/rest/operate/modify/zero/' + id + '?zero=' + $scope.unitchangezero).success(function (res) {
            if (res.error == 0) {
                layer.msg("修改成功");
            } else {
                layer.msg(res.message);
            }
            ;
            $scope.getUnitList();

        }).error(function () {
            layer.msg("保存失败")
        })

    }

    //版本列表初始化
    $scope.versionchooseDialog = function () {
        $scope.versionid = this.shebei.id; //获取当前列表的id
        $scope.checkversionid = "";
        $http.getData(serviceHttp + 'api/rest/operate/select/device/version').success(function (res) {
            $scope.versionlist = res.data;
        }).error(function () {
            alert("error")
        });
    }

    //选中版本
    $scope.checkboxid = function () {
        $scope.checkversionid = this.version.id; //获取当前列表的id
    }

    // 保存版本更新内容
    $scope.versionchoose = function () {


        var id = $scope.versionid;
        var deviceVersionId = $scope.checkversionid;

        $http.get(serviceHttp + '/api/rest/operate/update/device/version/' + id + '?deviceVersionId=' + deviceVersionId).success(function (res) {
            if (res.error == "1005") {
                layer.msg(res.message)
            } else {
            };
            $scope.getUnitList();
        }).error(function () {
            layer.msg("请选择需要更新的版本")
        })


    }

    $scope.getUnitList();
    $scope.redirect = function (url) {
        $location.url(url);
    }

}
indexapp.controller('unitlistController', unitlistInfo);